// File Path: monorepo/web/frontend/src/pages/Admin/Customer/Search/CriteriaPage.jsx

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

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

  // Form states
  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    organizationName: "",
    tags: [],
    showOnlyActive: true,
  });
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);

  // Check authentication on mount
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
    }
  }, [authManager, navigate]);

  // Breadcrumb configuration - memoized
  const breadcrumbItems = useMemo(() => [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Customers",
      to: "/admin/customers",
      icon: UserGroupIcon,
    },
    {
      label: "Advanced Search",
      isActive: true,
    },
  ], []);

  // Form sections configuration - memoized
  const formSections = useMemo(() => [
    {
      title: "Personal Information",
      fields: [
        {
          name: "firstName",
          label: "First Name",
          type: "text",
          placeholder: "Enter first name",
          icon: UserIcon,
        },
        {
          name: "lastName",
          label: "Last Name",
          type: "text",
          placeholder: "Enter last name",
          icon: UserIcon,
        },
      ],
    },
    {
      title: "Contact Information",
      fields: [
        {
          name: "email",
          label: "Email Address",
          type: "email",
          placeholder: "Enter email address",
          icon: EnvelopeIcon,
        },
        {
          name: "phone",
          label: "Phone Number",
          type: "tel",
          placeholder: "Enter phone number",
          icon: PhoneIcon,
        },
      ],
    },
    {
      title: "Organization Details",
      fields: [
        {
          name: "organizationName",
          label: "Organization Name",
          type: "text",
          placeholder: "Enter organization name",
          icon: BuildingOffice2Icon,
        },
      ],
    },
  ], []);

  // Checkbox options - memoized
  const checkboxOptions = useMemo(() => [
    {
      name: "showOnlyActive",
      label: "Show only active customers",
    },
  ], []);

  // Handle form submission - memoized
  const handleSubmit = useCallback((data) => {
    setIsLoading(true);

    // Validation
    if (
      !data.firstName &&
      !data.lastName &&
      !data.email &&
      !data.phone &&
      !data.organizationName
    ) {
      setErrors({
        message: "Please enter at least one search field",
      });
      setIsLoading(false);
      return;
    }

    // Clear errors
    setErrors({});

    // Build query parameters
    const queryParams = new URLSearchParams();
    if (data.firstName) queryParams.append("fn", data.firstName);
    if (data.lastName) queryParams.append("ln", data.lastName);
    if (data.email) queryParams.append("e", data.email);
    if (data.phone) queryParams.append("p", data.phone);
    if (data.organizationName) queryParams.append("on", data.organizationName);
    queryParams.append("active", data.showOnlyActive ? "1" : "0");

    // Navigate to results page
    const queryString = queryParams.toString();
    navigate(`/admin/customers/search-result${queryString ? `?${queryString}` : ""}`);
  }, [navigate]);

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

  // Handle clear form - memoized
  const handleClear = useCallback(() => {
    setFormData({
      firstName: "",
      lastName: "",
      email: "",
      phone: "",
      organizationName: "",
      tags: [],
      showOnlyActive: true,
    });
    setErrors({});
  }, []);

  return (
    <SearchCriteriaPageComponent
      breadcrumbItems={breadcrumbItems}
      pageTitle="Search Customers"
      pageIcon={MagnifyingGlassIcon}
      formTitle="Search Criteria"
      formSubtitle="Enter search criteria to find customers"
      formIcon={MagnifyingGlassIcon}
      formData={formData}
      onFormDataChange={setFormData}
      formSections={formSections}
      checkboxOptions={checkboxOptions}
      errors={errors}
      onSubmit={handleSubmit}
      onCancel={handleCancel}
      onClear={handleClear}
      submitLabel="Search Customers"
      isLoading={isLoading}
      loadingText="Searching..."
    />
  );
}

export default AdminCustomerSearchCriteriaPage;