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

import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router";
import {
  useCustomerManager,
  useEventOrderWizardStorage,
} from "../../../../services/Services";
import { WizardSearchStep, UIXThemeProvider } from "../../../../components/UIX";
import {
  TicketIcon,
  MagnifyingGlassIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  UserPlusIcon,
  CheckCircleIcon,
} from "@heroicons/react/24/outline";
import { Card } from "../../../../components/UI";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

function AdminEventOrderAddStep2PartAPage() {
  const navigate = useNavigate();
  const customerManager = useCustomerManager();
  const wizardStorage = useEventOrderWizardStorage();

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState(null);
  const [formData, setFormData] = useState({
    searchQuery: "",
    email: "",
    phone: "",
    firstName: "",
    lastName: "",
  });

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

  // Check for existing wizard data on mount
  useEffect(() => {
    const event = wizardStorage.getEvent();
    if (!event) {
      // No event selected, redirect back to step 1
      navigate("/admin/event-orders/add/step-1-search");
      return;
    }
    setSelectedEvent(event);
  }, [navigate, wizardStorage]);

  // Field configuration for search form - customer search criteria
  const searchFields = [
    {
      name: "searchQuery",
      label: "Quick Search",
      type: "text",
      placeholder: "Search by name, email, phone, or customer ID...",
      section: "quick",
      icon: MagnifyingGlassIcon,
    },
    {
      name: "firstName",
      label: "First Name",
      type: "text",
      placeholder: "Enter first name",
      section: "details",
      icon: UserIcon,
    },
    {
      name: "lastName",
      label: "Last Name",
      type: "text",
      placeholder: "Enter last name",
      section: "details",
      icon: UserIcon,
    },
    {
      name: "email",
      label: "Email Address",
      type: "email",
      placeholder: "customer@example.com",
      section: "contact",
      icon: EnvelopeIcon,
    },
    {
      name: "phone",
      label: "Phone Number",
      type: "tel",
      placeholder: "(555) 123-4567",
      section: "contact",
      icon: PhoneIcon,
    },
  ];

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

    // Check if at least one search criteria is provided
    if (
      !data.searchQuery?.trim() &&
      !data.email?.trim() &&
      !data.phone?.trim() &&
      !data.firstName?.trim() &&
      !data.lastName?.trim()
    ) {
      errors.message = "Please enter at least one search criteria";
    }

    // Validate email format if provided
    if (data.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
      errors.email = "Please enter a valid email address";
    }

    // Validate phone format if provided (basic validation)
    if (data.phone && !/^[\d\s\-+()]+$/.test(data.phone)) {
      errors.phone = "Please enter a valid phone number";
    }

    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.email?.trim()) {
      searchParams.append("email", data.email.trim());
    }
    if (data.phone?.trim()) {
      searchParams.append("phone", data.phone.trim());
    }
    if (data.firstName?.trim()) {
      searchParams.append("firstName", data.firstName.trim());
    }
    if (data.lastName?.trim()) {
      searchParams.append("lastName", data.lastName.trim());
    }

    // Clear any existing customer cache to force fresh search
    customerManager.clearCustomersCache();

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

  const handleSkipSearch = () => {
    // For event orders, redirect to customer creation if they want to skip search
    navigate("/admin/customers/add/step-1-search");
  };

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

  const handleBack = () => {
    navigate("/admin/event-orders/add/step-1-results");
  };

  // Clear error state on mount
  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);

  // Custom header with selected event info
  const renderHeader = () => {
    if (!selectedEvent) return null;

    return (
      <Card className="mb-6 bg-green-50 border-green-200">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-sm font-medium text-green-900">
              Selected Event
            </h3>
            <p className="mt-1 text-sm text-green-800">
              <strong>{selectedEvent.eventName}</strong>
              {selectedEvent.startDate && (
                <span className="ml-2 text-green-600">
                  • {formatDateForDisplay(selectedEvent.startDate)}
                </span>
              )}
            </p>
          </div>
          <CheckCircleIcon className="w-6 h-6 text-green-600" />
        </div>
      </Card>
    );
  };

  return (
    <UIXThemeProvider>
      {renderHeader()}
      <WizardSearchStep
        wizardSteps={wizardSteps}
        currentStep={2}
        wizardTitle="Create Event Order"
        wizardIcon={TicketIcon}
        formData={formData}
        onFormDataChange={setFormData}
        searchFields={searchFields}
        errors={errors}
        onSearch={handleSearch}
        onCancel={handleCancel}
        onBack={handleBack}
        onSkipSearch={handleSkipSearch}
        entityName="customer"
        isLoading={isLoading}
        skipIcon={UserPlusIcon}
        searchTitle="Search for Existing Customer"
        searchSubtitle="Find a customer to create an event order for the selected event"
        searchButtonLabel="Search Customers"
        skipButtonLabel="Create New Customer"
        skipDescription="If you need to create a new customer first, you can skip this search and go to the customer creation wizard"
      />
    </UIXThemeProvider>
  );
}

export default AdminEventOrderAddStep2PartAPage;
