// File Path: monorepo/web/frontend/src/pages/Admin/Division/Add/Step1SearchCriteriaPage.jsx

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

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

// Field configuration for search form - moved outside component
const SEARCH_FIELDS = [
  {
    name: "divisionName",
    label: "Division Name",
    type: "text",
    placeholder: "Enter division name",
    section: "division",
    icon: Cog6ToothIcon,
  },
  {
    name: "contactName",
    label: "Contact Name",
    type: "text",
    placeholder: "Enter contact name",
    section: "division",
    icon: UserIcon,
  },
  {
    name: "phone",
    label: "Phone Number",
    type: "tel",
    placeholder: "Enter phone number",
    section: "contact",
    icon: PhoneIcon,
  },
  {
    name: "email",
    label: "Email Address",
    type: "email",
    placeholder: "Enter email address",
    section: "contact",
    icon: EnvelopeIcon,
  },
];

function AdminDivisionAddStep1SearchCriteriaPage() {
  const navigate = useNavigate();
  const authManager = useAuthManager();
  const wizardStorage = useDivisionWizardStorage();

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

  // SECURITY: Authentication check and clear wizard state on mount (run once)
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    window.scrollTo(0, 0);
    wizardStorage.clearWizardData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Event handlers - memoized
  const handleSearch = useCallback((data) => {
    const { divisionName, contactName, email, phone } = data;
    if (!divisionName && !contactName && !email && !phone) {
      setErrors({
        message: "Please enter at least one search value",
      });
      return;
    }

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

    // Save search data to wizard storage
    const searchData = {
      divisionName,
      contactName,
      email,
      phone,
      timestamp: new Date().toISOString(),
    };
    wizardStorage.saveStepData("step1Data", searchData);

    // Navigate to results page with search parameters
    const searchParams = new URLSearchParams();
    if (divisionName) searchParams.append("dn", divisionName);
    if (contactName) searchParams.append("cn", contactName);
    if (email) searchParams.append("e", email);
    if (phone) searchParams.append("p", phone);

    navigate(`/admin/divisions/add/step-1-results?${searchParams.toString()}`);
  }, [wizardStorage, navigate]);

  const handleSkipSearch = useCallback(() => {
    // Clear and initialize wizard state
    wizardStorage.clearWizardData();

    // Save any entered data even when skipping search
    const searchData = {
      divisionName: formData.divisionName,
      contactName: formData.contactName,
      email: formData.email,
      phone: formData.phone,
      skipped: true,
      timestamp: new Date().toISOString(),
    };
    wizardStorage.saveStepData("step1Data", searchData);

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

  const handleCancel = useCallback(() => {
    // Clear any session storage data
    wizardStorage.clearWizardData();
    navigate("/admin/divisions");
  }, [wizardStorage, navigate]);

  return (
    <UIXThemeProvider>
      <WizardSearchStep
        wizardSteps={WIZARD_STEPS}
        currentStep={1}
        wizardTitle="Add New Division"
        wizardIcon={BuildingOffice2Icon}
        formData={formData}
        onFormDataChange={setFormData}
        searchFields={SEARCH_FIELDS}
        errors={errors}
        onSearch={handleSearch}
        onCancel={handleCancel}
        onSkipSearch={handleSkipSearch}
        entityName="division"
        isLoading={isLoading}
        skipIcon={BuildingOffice2Icon}
      />
    </UIXThemeProvider>
  );
}

export default AdminDivisionAddStep1SearchCriteriaPage;
