// File Path: monorepo/web/frontend/src/pages/Admin/EventContract/Add/Step1PartAPage.jsx

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import {
  useEventManager,
  useEventContractWizardStorage,
} from "../../../../services/Services";
import {
  WizardSearchStep,
  UIXThemeProvider,
} from "../../../../components/UIX";
import {
  TicketIcon,
  MagnifyingGlassIcon,
  CalendarIcon,
  MapPinIcon,
  UserGroupIcon,
  TagIcon,
  ClockIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";
import {
  EVENT_TYPE_OPTIONS,
  EVENT_STATUS_OPTIONS,
  EVENT_SHSM_OPTIONS,
  FACILITATOR_TIME_OPTIONS,
  DAY_OF_WEEK_OPTIONS,
} from "../../../../constants/Event";
import { ensureISODateForAPI } from "../../../../services/Helpers/DateFormatter";

function AdminEventContractStep1PartAPage() {
  const navigate = useNavigate();
  const eventManager = useEventManager();
  const wizardStorage = useEventContractWizardStorage();

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState({
    searchQuery: "",
    eventName: "",
    type: "",
    status: "1", // Default to Active
    isSHSM: "",
    startDateFrom: "",
    startDateTo: "",
    dayOfWeek: "",
    selectedSkillSets: "",
    selectedTags: "",
    facilitatorTime: "",
  });
  const [selectOptions, setSelectOptions] = useState({
    skillSets: [],
    tags: [],
  });
  const [loadingSelectOptions, setLoadingSelectOptions] = useState(false);
  const [selectedFacilitator, setSelectedFacilitator] = useState(null);

  // Handle unauthorized access
  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };

  // Clear wizard state on mount and check for existing data
  useEffect(() => {
    window.scrollTo(0, 0);

    const facilitator = wizardStorage.getFacilitator();
    if (facilitator) {
      setSelectedFacilitator(facilitator);
    }

    // Check if we already have an event selected
    const existingEvent = wizardStorage.getEvent();
    if (existingEvent) {
      // Pre-fill search with event name if coming back
      setFormData(prev => ({
        ...prev,
        eventName: existingEvent.eventName || "",
        type: existingEvent.type ? String(existingEvent.type) : "",
        status: existingEvent.status !== undefined ? String(existingEvent.status) : "1",
      }));
    }
  }, [wizardStorage]);

  // Load select options using EventManager
  useEffect(() => {
    loadSelectOptions();
  }, []);

  const loadSelectOptions = async () => {
    setLoadingSelectOptions(true);
    try {
      // Use EventManager to get select options (with caching)
      const options = await eventManager.getEventSelectOptions(onUnauthorized);

      // Transform skill sets and tags for MultiSelect component
      const skillSetOptions = (options.skillSets || []).map((item) => ({
        value: String(item.value),
        label: item.label || item.text,
      }));

      const tagOptions = (options.tags || []).map((item) => ({
        value: String(item.value),
        label: item.label || item.text,
      }));

      setSelectOptions({
        skillSets: skillSetOptions,
        tags: tagOptions,
      });
    } catch (err) {
      if (process.env.NODE_ENV === 'development') {
        console.error("Failed to load select options:", err);
      }
      setError(
        "Failed to load filter options. Some filters may not be available.",
      );
    } finally {
      setLoadingSelectOptions(false);
    }
  };

  // Configuration for wizard steps
  const wizardSteps = [
    { title: "Find Event" },
    { title: "Contract Details" },
    { title: "Attachments" },
    { title: "Review & Confirm" },
  ];

  // Field configuration for search form - preserving all existing search criteria
  const searchFields = [
    {
      name: "searchQuery",
      label: "Quick Search",
      type: "text",
      placeholder: "Search by event name, description, or location...",
      section: "quick",
      icon: MagnifyingGlassIcon,
    },
    {
      name: "eventName",
      label: "Event Name",
      type: "text",
      placeholder: "Enter event name",
      section: "details",
      icon: TicketIcon,
    },
    {
      name: "type",
      label: "Event Type",
      type: "text",
      placeholder: "e.g., Conference, FieldTrip, Virtual, InSchool",
      section: "details",
      icon: MapPinIcon,
    },
    {
      name: "status",
      label: "Status",
      type: "text",
      placeholder: "e.g., Active, Archived",
      section: "filters",
    },
    {
      name: "isSHSM",
      label: "SHSM Related",
      type: "text",
      placeholder: "Yes/No - Specialist High Skills Major",
      section: "filters",
      helperText: "Specialist High Skills Major",
    },
    {
      name: "startDateFrom",
      label: "Start Date From",
      type: "date",
      placeholder: "YYYY-MM-DD",
      section: "dates",
      icon: CalendarIcon,
      helperText: "Events starting on or after this date",
    },
    {
      name: "startDateTo",
      label: "Start Date To",
      type: "date",
      placeholder: "YYYY-MM-DD",
      section: "dates",
      icon: CalendarIcon,
      helperText: "Events starting on or before this date",
    },
    {
      name: "dayOfWeek",
      label: "Day of Week",
      type: "text",
      placeholder: "e.g., Monday, Tuesday, etc.",
      section: "timing",
      icon: CalendarIcon,
    },
    {
      name: "facilitatorTime",
      label: "Facilitator Time",
      type: "text",
      placeholder: "e.g., AM, PM, Both",
      section: "timing",
      icon: ClockIcon,
    },
    {
      name: "selectedSkillSets",
      label: "Skill Sets",
      type: "text",
      placeholder: loadingSelectOptions ? "Loading..." : "Enter skill set names (comma-separated)",
      section: "advanced",
      icon: UserGroupIcon,
    },
    {
      name: "selectedTags",
      label: "Tags",
      type: "text",
      placeholder: loadingSelectOptions ? "Loading..." : "Enter tag names (comma-separated)",
      section: "advanced",
      icon: TagIcon,
    },
  ];

  // Validate search criteria
  const validateSearchCriteria = (data) => {
    const errors = {};

    // Check if at least one search criteria is provided
    if (
      !data.searchQuery?.trim() &&
      !data.eventName?.trim() &&
      !data.type &&
      !data.isSHSM &&
      !data.startDateFrom &&
      !data.startDateTo &&
      !data.dayOfWeek &&
      !data.selectedSkillSets &&
      !data.selectedTags &&
      !data.facilitatorTime
    ) {
      errors.message = "Please enter at least one search criteria";
    }

    // Validate date range
    if (data.startDateFrom && data.startDateTo) {
      const fromDate = new Date(data.startDateFrom);
      const toDate = new Date(data.startDateTo);
      if (fromDate > toDate) {
        errors.dateRange = "Start date 'from' must be before or equal to 'to' date";
      }
    }

    return errors;
  };

  // Event handlers
  const handleSearch = (data) => {
    // Validate
    const errors = validateSearchCriteria(data);
    if (Object.keys(errors).length > 0) {
      setErrors(errors);
      return;
    }

    // Clear any previous errors
    setErrors({});

    // Build search params using form data
    const searchParams = new URLSearchParams();

    if (data.searchQuery?.trim()) {
      searchParams.append("q", data.searchQuery.trim());
    }
    if (data.eventName?.trim()) {
      searchParams.append("name", data.eventName.trim());
    }
    if (data.type) {
      searchParams.append("type", data.type);
    }
    if (data.status) {
      searchParams.append("status", data.status);
    }
    if (data.isSHSM) {
      searchParams.append("shsm", data.isSHSM);
    }
    if (data.startDateFrom) {
      searchParams.append("startFrom", data.startDateFrom);
    }
    if (data.startDateTo) {
      searchParams.append("startTo", data.startDateTo);
    }
    if (data.dayOfWeek) {
      searchParams.append("dow", data.dayOfWeek);
    }
    if (data.selectedSkillSets) {
      searchParams.append("skills", data.selectedSkillSets);
    }
    if (data.selectedTags) {
      searchParams.append("tags", data.selectedTags);
    }
    if (data.facilitatorTime) {
      searchParams.append("facTime", data.facilitatorTime);
    }

    // Clear any existing event cache to force fresh search
    eventManager.clearEventsCache();

    // Navigate to Step1Results with search params
    navigate(
      `/admin/event-contracts/add/step-1-results?${searchParams.toString()}`,
    );
  };

  const handleCancel = () => {
    navigate("/admin/event-contracts");
  };

  return (
    <UIXThemeProvider>
      <WizardSearchStep
        wizardSteps={wizardSteps}
        currentStep={1}
        wizardTitle="Create Event Contract"
        wizardIcon={TicketIcon}
        formData={formData}
        onFormDataChange={setFormData}
        searchFields={searchFields}
        errors={errors}
        onSearch={handleSearch}
        onCancel={handleCancel}
        onSkipSearch={null}
        entityName="event"
        isLoading={isLoading}
        searchTitle="Search for Existing Event"
        searchSubtitle="Find an event to create a contract for"
        searchButtonLabel="Search Events"
      />
    </UIXThemeProvider>
  );
}

export default AdminEventContractStep1PartAPage;
