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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import {
  useEventManager,
  useEventOrderWizardStorage,
} from "../../../../services/Services";
import {
  WizardSearchStep,
  UIXThemeProvider,
} from "../../../../components/UIX";
import {
  TicketIcon,
  MagnifyingGlassIcon,
  CalendarIcon,
  MapPinIcon,
  UserGroupIcon,
  TagIcon,
  ClockIcon,
} from "@heroicons/react/24/outline";

// Configuration for wizard steps - moved outside component
const WIZARD_STEPS = [
  { title: "Find Event" },
  { title: "Find Customer" },
  { title: "Order Requirements" },
  { title: "Additional Details" },
  { title: "Review & Confirm" },
];

// Field configuration for search form - moved outside component
const SEARCH_FIELDS = [
  {
    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: "Enter skill set names (comma-separated)",
    section: "advanced",
    icon: UserGroupIcon,
  },
  {
    name: "selectedTags",
    label: "Tags",
    type: "text",
    placeholder: "Enter tag names (comma-separated)",
    section: "advanced",
    icon: TagIcon,
  },
];

function AdminEventOrderAddStep1PartAPage() {
  const navigate = useNavigate();
  const eventManager = useEventManager();
  const wizardStorage = useEventOrderWizardStorage();

  // 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: "",
  });

  // Check if we already have an event selected (coming back from later steps)
  useEffect(() => {
    window.scrollTo(0, 0);

    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]);

  // Validate search criteria - memoized
  const validateSearchCriteria = useCallback((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 - memoized
  const handleSearch = useCallback((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-orders/add/step-1-results?${searchParams.toString()}`,
    );
  }, [validateSearchCriteria, navigate, eventManager]);

  const handleCancel = useCallback(() => {
    navigate("/admin/event-orders");
  }, [navigate]);

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

export default AdminEventOrderAddStep1PartAPage;
