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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useSearchParams } from "react-router";
import { useFacilitatorManager, useTagManager } from "../../../../services/Services";
import {
  MagnifyingGlassIcon,
  ArrowLeftIcon,
  EyeIcon,
  WrenchScrewdriverIcon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
  UserIcon,
  HomeIcon,
  PlusIcon,
  BuildingOffice2Icon,
} 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 {
  FACILITATOR_STATUS_FILTER_OPTIONS,
  FACILITATOR_TYPE_OF_FILTER_OPTIONS,
  FACILITATOR_SORT_OPTIONS,
  INDIVIDUAL_FACILITATOR_TYPE_OF_ID,
  REPRESENTATIVE_FACILITATOR_TYPE_OF_ID,
} from "../../../../constants/Facilitator";

function AdminFacilitatorSearchResultPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const facilitatorManager = useFacilitatorManager();
  const tagManager = useTagManager();
  const { getThemeClasses } = useUIXTheme();

  // List state
  const [facilitatorList, setFacilitatorList] = 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("lexical_name");
  const [sortOrder, setSortOrder] = useState("ASC");
  const [status, setStatus] = useState("");
  const [type, setType] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");

  // Extract search parameters from URL
  const searchCriteria = useMemo(() => {
    const criteria = [];
    const firstName = searchParams.get("fn");
    const lastName = searchParams.get("ln");
    const email = searchParams.get("e");
    const phone = searchParams.get("p");
    const organizationName = searchParams.get("on");
    const tags = searchParams.get("tags");
    const activeOnly = searchParams.get("active");

    if (firstName) criteria.push(`First Name: ${firstName}`);
    if (lastName) criteria.push(`Last Name: ${lastName}`);
    if (email) criteria.push(`Email: ${email}`);
    if (phone) criteria.push(`Phone: ${phone}`);
    if (organizationName) criteria.push(`Organization: ${organizationName}`);
    if (tags) {
      // Map tag IDs to labels
      const tagIds = tags.split(",");
      const tagLabels = tagIds
        .map((tagId) => {
          const tag = tagOptions.find((opt) => opt.value === tagId);
          return tag ? tag.label : tagId;
        })
        .join(", ");
      criteria.push(`Tags: ${tagLabels}`);
    }
    if (activeOnly) criteria.push("Active Only");

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

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

  // Action buttons configuration
  const actionButtons = [
    {
      label: "New Search",
      variant: "secondary",
      icon: ArrowLeftIcon,
      onClick: () => navigate("/admin/facilitators/search"),
    },
    {
      label: "Add Facilitator",
      variant: "success",
      icon: PlusIcon,
      onClick: () => navigate("/admin/facilitators/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("page_size", pageSize);

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

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

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

    // Add search params from URL
    const firstName = searchParams.get("fn");
    const lastName = searchParams.get("ln");
    const email = searchParams.get("e");
    const phone = searchParams.get("p");
    const organizationName = searchParams.get("on");
    const tags = searchParams.get("tags");
    const activeOnly = searchParams.get("active");

    if (firstName) map.set("first_name", firstName);
    if (lastName) map.set("last_name", lastName);
    if (email) map.set("email", email);
    if (phone) map.set("phone", phone);
    if (organizationName) map.set("organization_name", organizationName);
    if (tags) map.set("inTagIds", tags); // Backend expects in_tag_ids for "any of these tags"
    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 facilitators with useCallback to prevent infinite loops
  const fetchFacilitatorList = useCallback(
    (forceRefresh = false) => {
      setIsLoading(true);
      setErrors({});

      // Use the manager to fetch facilitators with force refresh flag
      facilitatorManager.getFacilitatorsWithFiltersMapWithCallbacks(
        filtersMap,
        (response) => {
          setFacilitatorList(response);

          // Update pagination state
          if (response.hasNextPage) {
            setNextCursor(response.nextCursor);
          } else {
            setNextCursor("");
          }
        },
        (error) => {
          console.error("Error fetching facilitator list:", error);
          setErrors(error);
        },
        () => {
          setIsLoading(false);
        },
        onUnauthorized,
        forceRefresh,
      );
    },
    [filtersMap, facilitatorManager, onUnauthorized],
  );

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

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

  // Get type badge component
  const getTypeBadge = (facilitatorType) => {
    const variantMap = {
      [INDIVIDUAL_FACILITATOR_TYPE_OF_ID]: "info",
      [REPRESENTATIVE_FACILITATOR_TYPE_OF_ID]: "warning",
    };
    const labelMap = {
      [INDIVIDUAL_FACILITATOR_TYPE_OF_ID]: "Individual",
      [REPRESENTATIVE_FACILITATOR_TYPE_OF_ID]: "Representative",
    };
    const variant = variantMap[facilitatorType] || "default";
    const label = labelMap[facilitatorType] || "Unknown";

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

  // Format phone number
  const formatPhone = (phone) => {
    if (!phone) return "—";
    const cleaned = phone.replace(/\D/g, "");
    const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
    if (match) {
      return `(${match[1]}) ${match[2]}-${match[3]}`;
    }
    return phone;
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Facilitator",
      accessor: "firstName",
      type: "text",
      render: (value, facilitator) => {
        const displayName = facilitator.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID
          ? (facilitator.organizationName || `${facilitator.firstName} ${facilitator.lastName}`)
          : `${facilitator.firstName} ${facilitator.lastName}`;
        return (
          <div className="flex items-center">
            {facilitator.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID ? (
              <BuildingOffice2Icon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            ) : (
              <UserIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            )}
            <div>
              <div className="font-medium">{displayName}</div>
              {facilitator.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID && facilitator.organizationName && (
                <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  {facilitator.firstName} {facilitator.lastName}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Contact",
      accessor: "email",
      render: (email, facilitator) => {
        if (!email && !facilitator.phone) return "—";
        return (
          <div className="space-y-1">
            {email && (
              <div className="flex items-center text-sm">
                <EnvelopeIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <a
                  href={`mailto:${email}`}
                  className={`transition-colors ${getThemeClasses('link-primary')}`}
                  onClick={(e) => e.stopPropagation()}
                >
                  {email}
                </a>
              </div>
            )}
            {facilitator.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <a
                  href={`tel:${facilitator.phone}`}
                  className={`transition-colors ${getThemeClasses('link-primary')}`}
                  onClick={(e) => e.stopPropagation()}
                >
                  {formatPhone(facilitator.phone)}
                </a>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Location",
      accessor: "city",
      render: (city, facilitator) => {
        if (!facilitator.addressLine1 && !facilitator.city && !facilitator.region) return "—";
        return (
          <div className="flex items-center text-sm">
            <MapPinIcon className={`w-4 h-4 mr-1 ${getThemeClasses('text-muted')}`} />
            <div>
              {facilitator.addressLine1 && <div>{facilitator.addressLine1}</div>}
              {(facilitator.city || facilitator.region) && (
                <div>
                  {[facilitator.city, facilitator.region].filter(Boolean).join(", ")}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Type",
      accessor: "type",
      render: (type) => getTypeBadge(type)
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, facilitator) => (
        <ViewButton
          to={`/admin/facilitator/${facilitator.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("lexical_name");
    setSortOrder("ASC");
    setStatus("");
    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 facilitators by name...",
    statusOptions: FACILITATOR_STATUS_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: FACILITATOR_TYPE_OF_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    typeFilter: type,
    onTypeFilterChange: handleTypeChange,
    sortOptions: FACILITATOR_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: () => fetchFacilitatorList(true)
  }), [searchQuery, tempSearchQuery, status, type, sortBy, sortOrder, pageSize, handleSearch, handleStatusChange, handleTypeChange, handleSortChange, handlePageSizeChange, handleClearFilters, fetchFacilitatorList]);

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

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

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

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

export default AdminFacilitatorSearchResultPage;