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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import { useAuthManager } from "../../../../services/Services";
import {
  WizardSearchStep,
  UIXThemeProvider,
} from "../../../../components/UIX";
import {
  UserPlusIcon,
  MagnifyingGlassIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  UserGroupIcon,
} from "@heroicons/react/24/outline";

// Configuration for wizard steps - moved outside component
const WIZARD_STEPS = [
  { title: "Search" },
  { title: "Type" },
  { title: "Contact" },
  { title: "Address" },
  { title: "Account" },
  { title: "Comments" },
];

// Field configuration for search form - moved outside component
const SEARCH_FIELDS = [
  {
    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: "Enter email address",
    section: "contact",
    icon: EnvelopeIcon,
  },
  {
    name: "phone",
    label: "Phone Number",
    type: "tel",
    placeholder: "Enter phone number",
    section: "contact",
    icon: PhoneIcon,
  },
];

function AdminCustomerAddStep1PartAPage() {
  const authManager = useAuthManager();
  const navigate = useNavigate();

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

  // Check authentication
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }
    window.scrollTo(0, 0);
  }, [authManager, navigate]);

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

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

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

    // Navigate to results page with search parameters
    navigate(
      `/admin/customers/add/step-1-results?${searchParams.toString()}`,
    );
  }, [validateSearchCriteria, navigate]);

  const handleSkipSearch = useCallback(() => {
    // Clear any existing customer creation state
    sessionStorage.removeItem("FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE");

    // Navigate directly to step 2
    navigate("/admin/customers/add/step-2");
  }, [navigate]);

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

  return (
    <UIXThemeProvider>
      <WizardSearchStep
        wizardSteps={WIZARD_STEPS}
        currentStep={1}
        wizardTitle="Add New Customer"
        wizardIcon={UserGroupIcon}
        formData={formData}
        onFormDataChange={setFormData}
        searchFields={SEARCH_FIELDS}
        errors={errors}
        onSearch={handleSearch}
        onCancel={handleCancel}
        onSkipSearch={handleSkipSearch}
        entityName="customer"
        isLoading={isLoading}
        skipIcon={UserPlusIcon}
        searchTitle="Search for Existing Customer"
        searchSubtitle="Check for existing customers before creating a new one"
        searchButtonLabel="Search Customers"
        skipButtonLabel="Add New Customer"
        skipDescription="If you're sure this is a new customer, skip the search and proceed directly to creation"
      />
    </UIXThemeProvider>
  );
}

export default AdminCustomerAddStep1PartAPage;
