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

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

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

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

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

  // Breadcrumb configuration
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Divisions",
      to: "/admin/divisions",
      icon: BuildingOffice2Icon,
    },
    {
      label: "Advanced Search",
      isActive: true,
    },
  ];

  // Form sections configuration
  const formSections = [
    {
      title: "Division Details",
      fields: [
        {
          name: "name",
          label: "Division Name",
          type: "text",
          placeholder: "Enter division name",
          icon: BuildingOffice2Icon,
        },
        {
          name: "organizationName",
          label: "Organization Name",
          type: "text",
          placeholder: "Enter parent organization name",
          icon: BuildingOffice2Icon,
        },
      ],
    },
    {
      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: "Location",
      fields: [
        {
          name: "city",
          label: "City",
          type: "text",
          placeholder: "Enter city",
          icon: MapPinIcon,
        },
        {
          name: "region",
          label: "Province/State",
          type: "text",
          placeholder: "Enter province or state",
          icon: MapPinIcon,
        },
      ],
    },
    {
      title: "Tags",
      columns: 1,
      fields: [
        {
          name: "tags",
          label: "",
          fieldType: "tags",
          placeholder: "Select tags to filter...",
          helperText: "Select one or more tags to filter results",
        },
      ],
    },
  ];


  // Checkbox options
  const checkboxOptions = [
    {
      name: "showOnlyActive",
      label: "Show only active divisions",
    },
  ];

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

    // Build query parameters
    const queryParams = new URLSearchParams();
    if (data.name) queryParams.append("name", data.name);
    if (data.email) queryParams.append("email", data.email);
    if (data.phone) queryParams.append("phone", data.phone);
    if (data.city) queryParams.append("city", data.city);
    if (data.region) queryParams.append("region", data.region);
    if (data.organizationName) queryParams.append("org", data.organizationName);
    if (data.tags && data.tags.length > 0) queryParams.append("tags", data.tags.join(","));
    if (data.showOnlyActive) queryParams.append("active_only", "true");

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

  // Handle cancel
  const handleCancel = () => {
    navigate("/admin/divisions");
  };

  // Handle clear form
  const handleClear = () => {
    setFormData({
      name: "",
      email: "",
      phone: "",
      city: "",
      region: "",
      organizationName: "",
      tags: [],
      showOnlyActive: true,
    });
    setErrors({});
  };

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

export default AdminDivisionSearchCriteriaPage;