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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Link, useNavigate, useSearchParams } from "react-router";
import { useDivisionManager } from "../../../../services/Services";
import {
  MagnifyingGlassIcon,
  ArrowLeftIcon,
  EyeIcon,
  BuildingOffice2Icon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
  HomeIcon,
  PlusIcon,
} from "@heroicons/react/24/outline";
import {
  SearchResultsPage,
  ViewButton,
  Badge,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  DIVISION_STATUS_OPTIONS,
  DIVISION_TYPE_OPTIONS,
  DIVISION_SORT_OPTIONS,
  DIVISION_TYPE_LABELS,
  DIVISION_STATUS_LABELS,
} from "../../../../constants/Division";

function AdminDivisionSearchResultPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const divisionManager = useDivisionManager();
  const tagManager = useTagManager();
  const { getThemeClasses } = useUIXTheme();

  // List state
  const [divisionList, setDivisionList] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [tagOptions, setTagOptions] = useState([]);

  // Pagination state (cursor-based)
  const [pageSize, setPageSize] = useState(25);
  const [previousCursors, setPreviousCursors] = useState([]);
  const [currentCursor, setCurrentCursor] = useState("");
  const [nextCursor, setNextCursor] = useState("");

  // Filter state
  const [sortBy, setSortBy] = useState("name");
  const [sortOrder, setSortOrder] = useState("ASC");
  const [status, setStatus] = useState("1"); // Default to active
  const [type, setType] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");

  // Extract search parameters from URL
  const searchCriteria = useMemo(() => {
    const criteria = [];
    const name = searchParams.get("name");
    const email = searchParams.get("email");
    const phone = searchParams.get("phone");
    const city = searchParams.get("city");
    const region = searchParams.get("region");
    const org = searchParams.get("org");
    const activeOnly = searchParams.get("active_only");

    if (name) criteria.push(`Name: ${name}`);
    if (email) criteria.push(`Email: ${email}`);
    if (phone) criteria.push(`Phone: ${phone}`);
    if (city) criteria.push(`City: ${city}`);
    if (region) criteria.push(`Region: ${region}`);
    if (org) criteria.push(`Organization: ${org}`);
    if (activeOnly) criteria.push("Active Only");

    return criteria;
  }, [searchParams, tagOptions]);

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

  // Action buttons configuration
  const actionButtons = [
    {
      label: "New Search",
      variant: "secondary",
      icon: ArrowLeftIcon,
      onClick: () => navigate("/admin/divisions/search"),
    },
    {
      label: "Add Division",
      variant: "success",
      icon: PlusIcon,
      onClick: () => navigate("/admin/divisions/add"),
    },
  ];

  // Handle unauthorized access
  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };
  // Fetch tag options on mount for label mapping
  useEffect(() => {
    const fetchTagOptions = async () => {
      try {
        const options = await tagManager.getTagSelectOptions(onUnauthorized, true);
        setTagOptions(options || []);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Error fetching tag options:", error);
        }
        setTagOptions([]);
      }
    };
    fetchTagOptions();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Run once on mount - tagManager and onUnauthorized are stable

  // Memoize filters map to prevent unnecessary rebuilds
  const filtersMap = useMemo(() => {
    const map = new Map();
    map.set("pageSize", pageSize);

    // Add cursor for pagination
    if (currentCursor) {
      map.set("cursor", currentCursor);
    }

    // Add sorting
    map.set("sortField", sortBy);
    map.set("sortOrder", sortOrder);

    // Add filters
    if (status !== "") {
      map.set("status", parseInt(status));
    }
    if (type !== "") {
      map.set("type", parseInt(type));
    }

    // Add search params from URL
    const name = searchParams.get("name");
    const email = searchParams.get("email");
    const phone = searchParams.get("phone");
    const city = searchParams.get("city");
    const region = searchParams.get("region");
    const org = searchParams.get("org");
    const activeOnly = searchParams.get("active_only");

    if (name) map.set("name", name);
    if (email) map.set("email", email);
    if (phone) map.set("phone", phone);
    if (city) map.set("city", city);
    if (region) map.set("region", region);
    if (org) map.set("organizationName", org);
    if (activeOnly) map.set("status", 1); // Active only

    if (searchQuery && searchQuery.trim()) {
      map.set("search", searchQuery.trim());
    }

    return map;
  }, [currentCursor, pageSize, sortBy, sortOrder, status, type, searchQuery, searchParams]);

  // Fetch divisions with useCallback to prevent infinite loops
  const fetchDivisionList = useCallback(
    (forceRefresh = false) => {
      setIsLoading(true);
      setErrors({});

      // Convert Map to object for the API
      const params = Object.fromEntries(filtersMap);

      // Use the manager to fetch divisions with force refresh flag
      divisionManager.getDivisionsWithCallbacks(
        params,
        (response) => {
          setDivisionList(response);

          // Update pagination state
          if (response.hasNextPage) {
            setNextCursor(response.nextCursor);
          } else {
            setNextCursor("");
          }
        },
        (error) => {
          if (process.env.NODE_ENV === 'development') {
            console.error("Error fetching division list:", error);
          }
          setErrors(error);
        },
        () => {
          setIsLoading(false);
        },
        onUnauthorized,
        forceRefresh,
      );
    },
    [filtersMap, divisionManager, onUnauthorized],
  );

  // Get status badge component
  const getStatusBadge = (divisionStatus) => {
    const variantMap = {
      1: "success", // Active
      0: "secondary", // Archived
    };
    const variant = variantMap[divisionStatus] || "default";
    const label = DIVISION_STATUS_LABELS[divisionStatus] || "Unknown";

    return (
      <Badge variant={variant} size="sm">
        {label}
      </Badge>
    );
  };

  // Get type badge component
  const getTypeBadge = (divisionType) => {
    const label = DIVISION_TYPE_LABELS[divisionType] || "Unknown";
    return (
      <Badge variant="info" size="sm">
        {label}
      </Badge>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Division",
      accessor: "divisionShortName",
      type: "text",
      render: (value, division) => {
        const shortName = division.divisionShortName || division.name || "Unnamed Division";
        const longName = division.divisionName || division.name;
        return (
          <div>
            <div className="font-medium">{shortName}</div>
            {longName && longName !== shortName && (
              <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                {longName}
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Contact",
      accessor: "contacts",
      render: (contacts) => {
        if (!contacts || !Array.isArray(contacts) || contacts.length === 0) {
          return "—";
        }
        const firstContact = contacts[0];
        const contactName = `${firstContact.firstName || ''} ${firstContact.lastName || ''}`.trim();
        return contactName || "—";
      }
    },
    {
      header: "Type",
      accessor: "divisionType",
      render: (type, division) => getTypeBadge(type || division.type)
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, division) => (
        <ViewButton
          onClick={() => navigate(`/admin/division/${division.id}`)}
        >
          View
        </ViewButton>
      )
    }
  ];

  // Pagination handlers
  const handlePageChange = (direction) => {
    if (direction === "next" && nextCursor) {
      const newPreviousCursors = [...previousCursors];
      newPreviousCursors.push(currentCursor);
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(nextCursor);
    } else if (direction === "previous" && previousCursors.length > 0) {
      const newPreviousCursors = [...previousCursors];
      const previousCursor = newPreviousCursors.pop();
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(previousCursor);
    }
  };

  // Search handler
  const handleSearch = () => {
    setSearchQuery(tempSearchQuery);
    // Reset pagination when search changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  // Filter change handlers
  const handleSortChange = (value) => {
    const [field, order] = value.split(",");
    setSortBy(field);
    setSortOrder(order);
    // Reset pagination when sort changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  const handleStatusChange = (value) => {
    setStatus(value);
    // Reset pagination when status changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  const handleTypeChange = (value) => {
    setType(value);
    // Reset pagination when type changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  const handlePageSizeChange = (value) => {
    setPageSize(value);
    // Reset pagination when page size changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  // Clear filters
  const handleClearFilters = () => {
    setSortBy("name");
    setSortOrder("ASC");
    setStatus("1");
    setType("");
    setSearchQuery("");
    setTempSearchQuery("");
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  // Memoize search filter configuration to prevent unnecessary re-renders
  const searchFilterConfig = useMemo(() => ({
    searchTerm: searchQuery,
    tempSearchTerm: tempSearchQuery,
    onSearchTermChange: setTempSearchQuery,
    onSearch: handleSearch,
    searchPlaceholder: "Search divisions by name...",
    statusOptions: DIVISION_STATUS_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: DIVISION_TYPE_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    typeFilter: type,
    onTypeFilterChange: handleTypeChange,
    sortOptions: DIVISION_SORT_OPTIONS,
    sortValue: `${sortBy},${sortOrder}`,
    onSortChange: handleSortChange,
    pageSizeOptions: PAGE_SIZE_OPTIONS.map(opt => ({
      value: opt.value,
      label: opt.label
    })),
    pageSize,
    onPageSizeChange: handlePageSizeChange,
    onClearFilters: handleClearFilters,
    onRefresh: () => fetchDivisionList(true)
  }), [searchQuery, tempSearchQuery, status, type, sortBy, sortOrder, pageSize, handleSearch, handleStatusChange, handleTypeChange, handleSortChange, handlePageSizeChange, handleClearFilters, fetchDivisionList]);

  // Memoize pagination configuration to prevent unnecessary re-renders
  const paginationConfig = useMemo(() => ({
    currentPage: previousCursors.length + 1,
    totalCount: divisionList?.count || 0,
    hasNextPage: !!nextCursor,
    onPageChange: (direction) => {
      if (direction > previousCursors.length + 1) {
        handlePageChange("next");
      } else {
        handlePageChange("previous");
      }
    }
  }), [previousCursors.length, divisionList?.count, nextCursor, handlePageChange]);

  // Initial load effect
  useEffect(() => {
    fetchDivisionList(true);
  }, []);

  // Effect for filter changes and pagination
  useEffect(() => {
    if (searchQuery || currentCursor) {
      fetchDivisionList(true);
    }
  }, [
    currentCursor,
    pageSize,
    sortBy,
    sortOrder,
    status,
    type,
    searchQuery,
  ]);

  return (
    <SearchResultsPage
      breadcrumbItems={breadcrumbItems}
      searchCriteria={searchCriteria}
      pageTitle="Division Search Results"
      actionButtons={actionButtons}
      results={divisionList?.results || []}
      columns={columns}
      isLoading={isLoading}
      errors={errors}
      searchFilter={searchFilterConfig}
      pagination={paginationConfig}
      emptyState={{
        icon: BuildingOffice2Icon,
        title: "No Divisions Found",
        description: "No divisions match your search criteria. Try adjusting your search terms or create a new division.",
        isCreateAction: true,
      }}
    />
  );
}

export default AdminDivisionSearchResultPage;