// File Path: monorepo/web/frontend/src/pages/Admin/Staff/Add/Step1ResultsPage.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useLocation } from "react-router";
import { useStaffManager, useStaffAddWizardStorage } from "../../../../services/Services";
import {
  UserPlusIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  BriefcaseIcon,
} from "@heroicons/react/24/outline";
import {
  WizardSearchResults,
  SelectButton,
  UIXThemeProvider,
  Badge,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  STAFF_TYPE_FILTER_OPTIONS,
  STAFF_STATUS_FILTER_OPTIONS,
  STAFF_SORT_OPTIONS,
  STAFF_TYPE_MAP,
  RESIDENTIAL_STAFF_TYPE_OF_ID,
  COMMERCIAL_STAFF_TYPE_OF_ID,
  STAFF_STATUS_ACTIVE,
  STAFF_STATUS_ARCHIVED,
} from "../../../../constants/Staff";

function AdminStaffAddStep1ResultsPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const staffManager = useStaffManager();
  const wizardStorage = useStaffAddWizardStorage();
  const { getThemeClasses } = useUIXTheme();

  // Configuration for wizard steps
  const wizardSteps = [
    { title: "Search" },
    { title: "Type" },
    { title: "Contact" },
    { title: "Address" },
    { title: "Account" },
    { title: "Metrics" },
    { title: "Comments" },
  ];

  // List state
  const [staffList, setStaffList] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = 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("1"); // Default to active
  const [type, setType] = useState("0"); // All types
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");

  // Extract search parameters from URL
  useEffect(() => {
    const urlParams = new URLSearchParams(location.search);
    const firstName = urlParams.get("fn") || "";
    const lastName = urlParams.get("ln") || "";
    const email = urlParams.get("e") || "";
    const phone = urlParams.get("p") || "";

    // Build search query from parameters
    const searchTerms = [firstName, lastName, email, phone].filter(Boolean);
    if (searchTerms.length > 0) {
      setSearchQuery(searchTerms.join(" "));
      setTempSearchQuery(searchTerms.join(" "));
    }
  }, [location.search]);

  // Handle unauthorized access
  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };

  // 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 !== "0") {
      map.set("status", parseInt(status));
    }

    if (type !== "0") {
      map.set("type", parseInt(type));
    }

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

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

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

      // Use the manager to fetch staff with force refresh flag
      staffManager.getStaffWithFiltersMapWithCallbacks(
        filtersMap,
        onFetchSuccess,
        onFetchError,
        onFetchDone,
        onUnauthorized,
        forceRefresh,
      );
    },
    [filtersMap, staffManager, onUnauthorized],
  );

  const onFetchSuccess = (response) => {
    setStaffList(response);

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

  const onFetchError = (error) => {
    if (import.meta.env.DEV) {
    console.error("Error fetching staff list:", error);
    setErrors(error);
    }
  };

  const onFetchDone = () => {
    setIsLoading(false);
  };

  // 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("1");
    setType("0");
    setSearchQuery("");
    setTempSearchQuery("");
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  // Get badge component for staff type
  const getTypeBadge = (staffType) => {
    const variantMap = {
      [RESIDENTIAL_STAFF_TYPE_OF_ID]: "info",
      [COMMERCIAL_STAFF_TYPE_OF_ID]: "warning",
    };
    const variant = variantMap[staffType] || "default";
    const label = STAFF_TYPE_MAP[staffType] || "Unknown";

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

  // Get badge component for staff status
  const getStatusBadge = (staffStatus) => {
    const variantMap = {
      [STAFF_STATUS_ACTIVE]: "success",
      [STAFF_STATUS_ARCHIVED]: "secondary",
    };
    const variant = variantMap[staffStatus] || "default";
    const labelMap = {
      [STAFF_STATUS_ACTIVE]: "Active",
      [STAFF_STATUS_ARCHIVED]: "Archived",
    };
    const label = labelMap[staffStatus] || "Unknown";

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

  // Column configuration for DataList
  const columns = [
    {
      header: "Staff",
      accessor: "firstName",
      type: "text",
      render: (value, staff) => {
        const displayName = staff.type === COMMERCIAL_STAFF_TYPE_OF_ID
          ? (staff.organizationName || `${staff.firstName} ${staff.lastName}`)
          : `${staff.firstName} ${staff.lastName}`;
        return (
          <div className="flex items-center">
            {staff.type === COMMERCIAL_STAFF_TYPE_OF_ID ? (
              <BriefcaseIcon 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>
              {staff.type === COMMERCIAL_STAFF_TYPE_OF_ID && staff.organizationName && (
                <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  {staff.firstName} {staff.lastName}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Contact",
      accessor: "email",
      render: (email, staff) => {
        if (!email && !staff.phone) return "—";
        return (
          <div className="space-y-1">
            {email && (
              <div className="flex items-center text-sm">
                <EnvelopeIcon className="w-4 h-4 mr-2 text-gray-400" />
                <a
                  href={`mailto:${email}`}
                  className={`transition-colors ${getThemeClasses('link-primary')}`}
                  onClick={(e) => e.stopPropagation()}
                >
                  {email}
                </a>
              </div>
            )}
            {staff.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className="w-4 h-4 mr-2 text-gray-400" />
                <a
                  href={`tel:${staff.phone}`}
                  className={`transition-colors ${getThemeClasses('link-primary')}`}
                  onClick={(e) => e.stopPropagation()}
                >
                  {staff.phone}
                </a>
              </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, staff) => (
        <SelectButton
          onClick={(e) => handleSelectStaff(staff, e)}
        >
          Select
        </SelectButton>
      )
    }
  ];

  // Handle staff selection
  const handleSelectStaff = (staff, event) => {
    // Prevent event bubbling to parent elements
    if (event) {
      event.stopPropagation();
      event.preventDefault();
    }

    // Validate staff ID exists
    if (!staff.id) {
      console.error("Staff ID is missing from staff object:", staff);
      setErrors({ general: "Cannot select staff: ID is missing" });
      return;
    }

    // Navigate to staff detail lite page
    // Note: When user selects an existing staff member, we navigate to their detail page
    // This allows them to view the existing record instead of creating a duplicate
    navigate(`/admin/staff/${staff.id}`);
  };

  // Memoize search filter configuration to prevent unnecessary re-renders
  const searchFilterConfig = useMemo(() => ({
    searchTerm: searchQuery,
    tempSearchTerm: tempSearchQuery,
    onSearchTermChange: setTempSearchQuery,
    onSearch: handleSearch,
    searchPlaceholder: "Search staff by name, email, or phone...",
    statusOptions: STAFF_STATUS_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: STAFF_TYPE_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    typeFilter: type,
    onTypeFilterChange: handleTypeChange,
    sortOptions: STAFF_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: () => fetchStaffList(true)
  }), [searchQuery, tempSearchQuery, status, type, sortBy, sortOrder, pageSize, handleSearch, handleStatusChange, handleTypeChange, handleSortChange, handlePageSizeChange, handleClearFilters, fetchStaffList]);

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

  // Action handlers
  const handleSearchAgain = () => {
    navigate("/admin/staff/add/step-1-search");
  };

  const handleAddNew = () => {
    // Reset wizard state
    wizardStorage.resetWizardState();
    // Navigate directly to step 2
    navigate("/admin/staff/add/step-2");
  };

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

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

  return (
    <UIXThemeProvider>
      <WizardSearchResults
        wizardSteps={wizardSteps}
        currentStep={1}
        wizardTitle="Add New Staff Member"
        wizardIcon={UserPlusIcon}
        data={staffList?.results || []}
        columns={columns}
        isLoading={isLoading}
        errors={errors}
        searchFilter={searchFilterConfig}
        pagination={paginationConfig}
        entityName="staff member"
        onSearchAgain={handleSearchAgain}
        onAddNew={handleAddNew}
        emptyState={{
          icon: UserIcon,
          title: "No Staff Found",
          description: "No staff members match your search criteria. Try adjusting your search terms or create a new staff member.",
          isCreateAction: true,
        }}
      />
    </UIXThemeProvider>
  );
}

export default AdminStaffAddStep1ResultsPage;