// File Path: monorepo/web/frontend/src/pages/Admin/Staff/Search/ResultPage.jsx
import React, { useState, useEffect, useCallback, useMemo, memo } from "react";
import { Link, useNavigate, useSearchParams } from "react-router";
import { useStaffManager } from "../../../../services/Services";
import {
  MagnifyingGlassIcon,
  UserGroupIcon,
  ArrowLeftIcon,
  PhoneIcon,
  EnvelopeIcon,
  ArchiveBoxIcon,
  EyeIcon,
  CheckCircleIcon,
  UserIcon,
  BriefcaseIcon,
  PencilIcon,
  HomeIcon,
  ChevronRightIcon,
} from "@heroicons/react/24/outline";
import {
  SearchResultsPage,
  ViewButton,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  STAFF_TYPE_MAP,
  STAFF_TYPE_FILTER_OPTIONS,
  STAFF_STATUS_FILTER_OPTIONS,
  STAFF_SORT_OPTIONS,
} from "../../../../constants/Staff";

// Static page size options
const PAGE_SIZE_OPTIONS = [10, 25, 50, 100];

// Static breadcrumb configuration
const BREADCRUMB_ITEMS = [
  {
    label: 'Dashboard',
    to: '/admin/dashboard',
    icon: HomeIcon
  },
  {
    label: 'Staff',
    to: '/admin/staff',
    icon: UserGroupIcon
  },
  {
    label: 'Search',
    to: '/admin/staff/search',
    icon: MagnifyingGlassIcon
  },
  {
    label: 'Results',
    icon: MagnifyingGlassIcon,
    isActive: true
  }
];

const AdminStaffSearchResultPageContent = memo(function AdminStaffSearchResultPageContent() {
  const navigate = useNavigate();
  const staffManager = useStaffManager();
  const tagManager = useTagManager();
  const [searchParams] = useSearchParams();
  const { getThemeClasses } = useUIXTheme();

  // Memoized theme classes
  const themeClasses = useMemo(() => ({
    textMuted: getThemeClasses('text-muted'),
    linkPrimary: getThemeClasses('link-primary'),
    badgeSecondary: getThemeClasses('badge-secondary'),
    badgeSuccess: getThemeClasses('badge-success'),
  }), [getThemeClasses]);

  // Extract search parameters from URL
  const firstName = searchParams.get("fn") || "";
  const lastName = searchParams.get("ln") || "";
  const email = searchParams.get("e") || "";
  const phone = searchParams.get("p") || "";
  const isActive = searchParams.get("active") === "1";

  // List state
  const [staffList, setStaffList] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [tagOptions, setTagOptions] = useState([]);
  const [successMessage, setSuccessMessage] = useState("");

  // Search filter state
  const [searchTerm, setSearchTerm] = useState("");
  const [tempSearchTerm, setTempSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState(isActive ? "1" : "");
  const [typeFilter, setTypeFilter] = useState("");
  const [sortValue, setSortValue] = useState("lexical_name,ASC");
  const [pageSize, setPageSize] = useState(50);

  // Pagination state
  const [previousCursors, setPreviousCursors] = useState([]);
  const [currentCursor, setCurrentCursor] = useState("");
  const [nextCursor, setNextCursor] = useState("");

  // Memoized callbacks
  const onFetchSuccess = useCallback((response) => {
    setStaffList(response);

    // Update pagination state
    if (response.hasNextPage) {
      setNextCursor(response.nextCursor);
    } else {
      setNextCursor("");
    }
  }, []);

  const onFetchError = useCallback((error) => {
    if (import.meta.env.DEV) {
    console.error("Error fetching search results:", error);
    setErrors(error);
    }
    window.scrollTo(0, 0);
  }, []);

  const onFetchDone = useCallback(() => {
    setIsLoading(false);
  }, []);

  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Fetch staff list based on search criteria
  const fetchStaffList = useCallback(() => {

    setIsLoading(true);
    setErrors({});

    // Build filters map for the API
    const filtersMap = new Map();
    filtersMap.set("pageSize", pageSize);

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

    // Add sorting
    const [sortField, sortOrder] = sortValue.split(",");
    filtersMap.set("sortField", sortField);
    filtersMap.set("sortOrder", sortOrder);

    // Add search criteria from URL
    if (firstName) filtersMap.set("first_name", firstName);
    if (lastName) filtersMap.set("last_name", lastName);
    if (email) filtersMap.set("email", email);
    if (phone) filtersMap.set("phone", phone);

    // Add filters
    if (statusFilter) {
      filtersMap.set("status", parseInt(statusFilter));
    }

    if (typeFilter) {
      filtersMap.set("type", parseInt(typeFilter));
    }

    // Use the manager to fetch staff with force refresh
    staffManager.getStaffWithFiltersMapWithCallbacks(
      filtersMap,
      onFetchSuccess,
      onFetchError,
      onFetchDone,
      onUnauthorized,
      true, // Force refresh to bypass cache
    );
  }, [
    firstName,
    lastName,
    email,
    phone,
    currentCursor,
    pageSize,
    sortValue,
    statusFilter,
    typeFilter,
    staffManager,
    onFetchSuccess,
    onFetchError,
    onFetchDone,
    onUnauthorized,
  ]);

  // Search and filter handlers
  const handleSearchTermChange = useCallback((value) => {
    setTempSearchTerm(value);
  }, []);

  const handleSearch = useCallback(() => {
    setSearchTerm(tempSearchTerm);
    setPreviousCursors([]);
    setCurrentCursor("");
  }, [tempSearchTerm]);

  const handleStatusFilterChange = useCallback((value) => {
    setStatusFilter(value);
    setPreviousCursors([]);
    setCurrentCursor("");
  }, []);

  const handleTypeFilterChange = useCallback((value) => {
    setTypeFilter(value);
    setPreviousCursors([]);
    setCurrentCursor("");
  }, []);

  const handleSortChange = useCallback((value) => {
    setSortValue(value);
    setPreviousCursors([]);
    setCurrentCursor("");
  }, []);

  const handlePageSizeChange = useCallback((value) => {
    setPageSize(value);
    setPreviousCursors([]);
    setCurrentCursor("");
  }, []);

  const handleClearFilters = useCallback(() => {
    setSearchTerm("");
    setTempSearchTerm("");
    setStatusFilter("");
    setTypeFilter("");
    setSortValue("lexical_name,ASC");
    setPageSize(50);
    setPreviousCursors([]);
    setCurrentCursor("");
  }, []);

  const handleRefresh = useCallback(() => {
    fetchStaffList();
  }, [fetchStaffList]);

  // Pagination handlers
  const handlePageChange = useCallback((direction) => {
    if (direction === 1 && nextCursor) {
      // Next page
      const newPreviousCursors = [...previousCursors];
      newPreviousCursors.push(currentCursor);
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(nextCursor);
    } else if (direction === -1 && previousCursors.length > 0) {
      // Previous page
      const newPreviousCursors = [...previousCursors];
      const previousCursor = newPreviousCursors.pop();
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(previousCursor);
    }
  }, [nextCursor, previousCursors, currentCursor]);


  // Format phone number
  const formatPhone = useCallback((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;
  }, []);

  // Get type badge
  const getTypeBadge = useCallback((typeValue) => {
    if (!typeValue) return null;
    const typeLabel = STAFF_TYPE_MAP[typeValue];

    return (
      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${themeClasses.badgeSecondary}`}>
        <BriefcaseIcon className="h-3 w-3 mr-1" />
        {typeLabel}
      </span>
    );
  }, [themeClasses.badgeSecondary]);

  // Get status badge
  const getStatusBadge = useCallback((statusValue) => {
    if (!statusValue) return null;
    const isActive = statusValue === 1;
    const badgeClass = isActive ? themeClasses.badgeSuccess : themeClasses.badgeSecondary;

    return (
      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${badgeClass}`}>
        {isActive ? 'Active' : 'Archived'}
      </span>
    );
  }, [themeClasses.badgeSuccess, themeClasses.badgeSecondary]);

  // Build search criteria display - memoized
  const searchCriteria = useMemo(() => {
    const criteria = [];
    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}`);
    criteria.push(`Status: ${isActive ? "Active Only" : "All"}`);
    return criteria;
  }, [firstName, lastName, email, phone, isActive]);

  // Calculate pagination - memoized
  const paginationData = useMemo(() => ({
    currentPage: previousCursors.length + 1,
    totalCount: staffList?.count || 0,
    hasNextPage: !!nextCursor,
  }), [previousCursors.length, staffList?.count, nextCursor]);

  // Define columns for DataList - memoized
  const columns = useMemo(() => [
    {
      header: "Name",
      accessor: "name",
      type: "link",
      linkPath: "/admin/staff/:id",
      render: (value, staff) => {
        const displayName = staff.name || `${staff.firstName} ${staff.lastName}`;
        return displayName;
      }
    },
    {
      header: "Email",
      accessor: "email",
      render: (value) => {
        if (!value) return <span className={`${themeClasses.textMuted} italic`}>—</span>;
        return (
          <a href={`mailto:${value}`} className={themeClasses.linkPrimary}>
            {value}
          </a>
        );
      }
    },
    {
      header: "Phone",
      accessor: "phone",
      render: (value) => {
        if (!value) return <span className={`${themeClasses.textMuted} italic`}>—</span>;
        return (
          <a href={`tel:${value}`} className={themeClasses.linkPrimary}>
            {formatPhone(value)}
          </a>
        );
      }
    },
    {
      header: "Type",
      accessor: "type",
      align: "center",
      render: (value) => getTypeBadge(value)
    },
    {
      header: "Status",
      accessor: "status",
      align: "center",
      render: (value) => getStatusBadge(value)
    },
    {
      header: "Actions",
      align: "center",
      render: (value, staff) => (
        <div className="flex items-center justify-center">
          <ViewButton
            to={`/admin/staff/${staff.id}`}
            text="View"
            aria-label={`View details for ${staff.name || `${staff.firstName} ${staff.lastName}`}`}
          />
        </div>
      )
    }
  ], [formatPhone, getTypeBadge, getStatusBadge, navigate, themeClasses]);

  // Effect to fetch data when component mounts or filters change
  useEffect(() => {
    fetchStaffList();
  }, [fetchStaffList]);

  // Configure action buttons - memoized
  const actionButtons = useMemo(() => [
    {
      variant: "secondary",
      onClick: () => navigate('/admin/staff/search'),
      icon: ArrowLeftIcon,
      label: "Back to Search"
    },
    {
      variant: "outline",
      onClick: () => navigate('/admin/staff'),
      label: "Back to Staff"
    }
  ], [navigate]);

  // Configure search filter - memoized
  const searchFilter = useMemo(() => ({
    searchTerm,
    tempSearchTerm,
    onSearchTermChange: handleSearchTermChange,
    onSearch: handleSearch,
    searchPlaceholder: "Search staff...",
    statusOptions: STAFF_STATUS_FILTER_OPTIONS,
    statusFilter,
    onStatusFilterChange: handleStatusFilterChange,
    typeOptions: STAFF_TYPE_FILTER_OPTIONS,
    typeFilter,
    onTypeFilterChange: handleTypeFilterChange,
    sortOptions: STAFF_SORT_OPTIONS,
    sortValue,
    onSortChange: handleSortChange,
    pageSizeOptions: PAGE_SIZE_OPTIONS,
    pageSize,
    onPageSizeChange: handlePageSizeChange,
    onClearFilters: handleClearFilters,
    onRefresh: handleRefresh,
  }), [searchTerm, tempSearchTerm, handleSearchTermChange, handleSearch, statusFilter,
      handleStatusFilterChange, typeFilter, handleTypeFilterChange, sortValue,
      handleSortChange, pageSize, handlePageSizeChange, handleClearFilters, handleRefresh]);

  // Configure pagination - memoized
  const pagination = useMemo(() => ({
    currentPage: paginationData.currentPage,
    totalCount: paginationData.totalCount,
    hasNextPage: paginationData.hasNextPage,
    onPageChange: handlePageChange,
  }), [paginationData, handlePageChange]);

  // Configure empty state - memoized
  const emptyState = useMemo(() => ({
    icon: UserGroupIcon,
    title: "No Staff Members Found",
    description: "No staff members match your search criteria. Try adjusting your search terms or filters.",
    actionLabel: "Try New Search",
    onActionClick: () => navigate('/admin/staff/search'),
    showAction: true,
  }), [navigate]);

  return (
    <SearchResultsPage
      breadcrumbItems={BREADCRUMB_ITEMS}
      searchCriteria={searchCriteria}
      pageTitle="Staff Search Results"
      actionButtons={actionButtons}
      results={staffList?.results || []}
      columns={columns}
      isLoading={isLoading}
      errors={errors}
      successMessage={successMessage}
      onSuccessMessageClose={() => setSuccessMessage('')}
      searchFilter={searchFilter}
      pagination={pagination}
      emptyState={emptyState}
    />
  );
});

AdminStaffSearchResultPageContent.displayName = "AdminStaffSearchResultPageContent";

function AdminStaffSearchResultPage() {
  return (
    <UIXThemeProvider>
      <AdminStaffSearchResultPageContent />
    </UIXThemeProvider>
  );
}

export default AdminStaffSearchResultPage;
