// monorepo/web/frontend/src/pages/Admin/Organization/Add/Step1SearchCriteriaPage.jsx

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

function AdminOrganizationAddStep1SearchCriteriaPage() {
  const navigate = useNavigate();
  const wizardStorage = useOrganizationWizardStorage();

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

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

  // Configuration for wizard steps
  const wizardSteps = [
    { title: "Search" },
    { title: "Type" },
    { title: "Contact" },
    { title: "Address" },
    { title: "Additional" },
    { title: "Review" },
  ];

  // Field configuration for search form
  const searchFields = [
    {
      name: "organizationName",
      label: "Organization Name",
      type: "text",
      placeholder: "Enter organization name",
      section: "organization",
      icon: Cog6ToothIcon,
    },
    {
      name: "contactName",
      label: "Contact Name",
      type: "text",
      placeholder: "Enter contact name",
      section: "organization",
      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,
    },
  ];

  // Event handlers
  const handleSearch = (data) => {
    // console.log("handleSearch: Beginning...", data);

    const { organizationName, contactName, email, phone } = data;
    if (!organizationName && !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 = {
      organizationName,
      contactName,
      email,
      phone,
      timestamp: new Date().toISOString(),
    };
    wizardStorage.saveStepData("step1Data", searchData);

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

    navigate(`/admin/organizations/add/step-1-results?${searchParams.toString()}`);
  };

  const handleSkipSearch = () => {
    // console.log("Creating new organization - skipping search");

    // Clear and initialize wizard state
    wizardStorage.clearWizardData();

    // Save any entered data even when skipping search
    const searchData = {
      organizationName: formData.organizationName,
      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/organizations/add/step-2");
  };

  const handleCancel = () => {
    // Clear any session storage data
    wizardStorage.clearWizardData();
    navigate("/admin/organizations");
  };

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

export default AdminOrganizationAddStep1SearchCriteriaPage;