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

import React, { useState, useEffect, useCallback, useMemo, memo } from "react";
import { useNavigate, useSearchParams } from "react-router";
import {
  useAuthManager,
  useStaffManager,
  useStaffAddWizardStorage,
} from "../../../../services/Services";
import {
  UserPlusIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  UsersIcon,
  HomeIcon,
  BuildingOffice2Icon,
  MapPinIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  WizardSearchResults,
  Badge,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  STAFF_STATUS_FILTER_OPTIONS,
  STAFF_TYPE_FILTER_OPTIONS,
  STAFF_SORT_OPTIONS,
  RESIDENTIAL_STAFF_TYPE_OF_ID,
  COMMERCIAL_STAFF_TYPE_OF_ID,
} from "../../../../constants/Staff";

// Configuration for wizard steps - moved outside component
const WIZARD_STEPS = [
  { title: "Search" },
  { title: "Type" },
  { title: "Contact" },
  { title: "Address" },
  { title: "Account" },
  { title: "Metrics" },
  { title: "Comments" },
];

// PERFORMANCE: Pre-mapped filter options to avoid repeated .map() calls
const MAPPED_STATUS_OPTIONS = STAFF_STATUS_FILTER_OPTIONS.map(opt => ({
  value: opt.value.toString(),
  label: opt.label,
}));

const MAPPED_TYPE_OPTIONS = STAFF_TYPE_FILTER_OPTIONS.map(opt => ({
  value: opt.value.toString(),
  label: opt.label,
}));

const MAPPED_PAGE_SIZE_OPTIONS = PAGE_SIZE_OPTIONS.map(opt => ({
  value: opt.value,
  label: opt.label,
}));

function AdminStaffAddStep1PartBPage() {
  const authManager = useAuthManager();
  const staffManager = useStaffManager();
  const wizardStorage = useStaffAddWizardStorage();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  // URL Parameters
  const firstName = searchParams.get("fn") || "";
  const lastName = searchParams.get("ln") || "";
  const email = searchParams.get("e") || "";
  const phone = searchParams.get("p") || "";

  // Component states
  const [errors, setErrors] = useState({});
  const [staffList, setStaffList] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

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

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

  // Check authentication
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }
    window.scrollTo(0, 0);
  }, [authManager, navigate]);

  return (
    <UIXThemeProvider>
      <AdminStaffAddStep1PartBPageContent
        staffManager={staffManager}
        wizardStorage={wizardStorage}
        navigate={navigate}
        firstName={firstName}
        lastName={lastName}
        email={email}
        phone={phone}
        errors={errors}
        setErrors={setErrors}
        staffList={staffList}
        setStaffList={setStaffList}
        isLoading={isLoading}
        setIsLoading={setIsLoading}
        pageSize={pageSize}
        setPageSize={setPageSize}
        previousCursors={previousCursors}
        setPreviousCursors={setPreviousCursors}
        nextCursor={nextCursor}
        setNextCursor={setNextCursor}
        currentCursor={currentCursor}
        setCurrentCursor={setCurrentCursor}
        searchQuery={searchQuery}
        setSearchQuery={setSearchQuery}
        tempSearchQuery={tempSearchQuery}
        setTempSearchQuery={setTempSearchQuery}
        sortBy={sortBy}
        setSortBy={setSortBy}
        sortOrder={sortOrder}
        setSortOrder={setSortOrder}
        status={status}
        setStatus={setStatus}
        type={type}
        setType={setType}
      />
    </UIXThemeProvider>
  );
}

// PERFORMANCE: Content component with optimized re-renders
function AdminStaffAddStep1PartBPageContent({
  staffManager,
  wizardStorage,
  navigate,
  firstName,
  lastName,
  email,
  phone,
  errors,
  setErrors,
  staffList,
  setStaffList,
  isLoading,
  setIsLoading,
  pageSize,
  setPageSize,
  previousCursors,
  setPreviousCursors,
  nextCursor,
  setNextCursor,
  currentCursor,
  setCurrentCursor,
  searchQuery,
  setSearchQuery,
  tempSearchQuery,
  setTempSearchQuery,
  sortBy,
  setSortBy,
  sortOrder,
  setSortOrder,
  status,
  setStatus,
  type,
  setType,
}) {
  const { getThemeClasses } = useUIXTheme();

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

  // 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
    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 (searchQuery && searchQuery.trim()) {
      map.set("search", searchQuery.trim());
    }

    return map;
  }, [currentCursor, pageSize, sortBy, sortOrder, status, type, searchQuery, firstName, lastName, email, phone]);

  // Fetch staff 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,
        (response) => {
          setStaffList(response);

          // Update pagination state
          if (response.hasNextPage) {
            setNextCursor(response.nextCursor);
          } else {
            setNextCursor("");
          }
        },
        (error) => {
          if (import.meta.env.DEV) {
          console.error("Error fetching staff list:", error);
          setErrors(error);
          }
        },
        () => {
          setIsLoading(false);
        },
        onUnauthorized,
        forceRefresh,
      );
    },
    [filtersMap, staffManager, onUnauthorized, setIsLoading, setErrors, setStaffList, setNextCursor],
  );

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

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

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

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

  // 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;
  }, []);

  // Column configuration for DataList
  const columns = useMemo(() => [
    {
      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 ? (
              <BuildingOffice2Icon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            ) : (
              <HomeIcon 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()}
                >
                  {formatPhone(staff.phone)}
                </a>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Location",
      accessor: "city",
      render: (city, staff) => {
        if (!staff.addressLine1 && !staff.city && !staff.region) return "—";
        return (
          <div className="flex items-center text-sm">
            <MapPinIcon className="w-4 h-4 mr-1 text-gray-400" />
            <div>
              {staff.addressLine1 && <div>{staff.addressLine1}</div>}
              {(staff.city || staff.region) && (
                <div>
                  {[staff.city, staff.region].filter(Boolean).join(", ")}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Type",
      accessor: "type",
      render: (type) => getTypeBadge(type)
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
  ], [formatPhone, getTypeBadge, getStatusBadge]); // getThemeClasses removed - captured in closure

  // Pagination handlers
  const handlePageChange = useCallback((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);
    }
  }, [nextCursor, previousCursors, currentCursor, setPreviousCursors, setCurrentCursor]);

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

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

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

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

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

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

  // PERFORMANCE: Memoize search filter configuration with pre-mapped options
  const searchFilterConfig = useMemo(() => ({
    searchTerm: searchQuery,
    tempSearchTerm: tempSearchQuery,
    onSearchTermChange: setTempSearchQuery,
    onSearch: handleSearch,
    searchPlaceholder: "Search staff by name...",
    statusOptions: MAPPED_STATUS_OPTIONS,
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: MAPPED_TYPE_OPTIONS,
    typeFilter: type,
    onTypeFilterChange: handleTypeChange,
    sortOptions: STAFF_SORT_OPTIONS,
    sortValue: `${sortBy},${sortOrder}`,
    onSortChange: handleSortChange,
    pageSizeOptions: MAPPED_PAGE_SIZE_OPTIONS,
    pageSize,
    onPageSizeChange: handlePageSizeChange,
    onClearFilters: handleClearFilters,
    onRefresh: () => fetchStaffList(true)
  }), [searchQuery, tempSearchQuery, status, type, sortBy, sortOrder, pageSize, handleSearch, handleStatusChange, handleTypeChange, handleSortChange, handlePageSizeChange, handleClearFilters, fetchStaffList, setTempSearchQuery]);

  // 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 = useCallback(() => {
    navigate("/admin/staff/add/step-1-search");
  }, [navigate]);

  const handleAddNew = useCallback(() => {
    // Clear any existing staff creation state
    wizardStorage.resetWizardState();
    navigate("/admin/staff/add/step-2");
  }, [navigate, wizardStorage]);

  // PERFORMANCE: Consolidated effect for initial load and filter changes
  // Prevents duplicate API calls on mount
  useEffect(() => {
    fetchStaffList(true);
  }, [
    currentCursor,
    pageSize,
    sortBy,
    sortOrder,
    status,
    type,
    searchQuery,
  ]);

  return (
    <WizardSearchResults
      wizardSteps={WIZARD_STEPS}
      currentStep={1}
      wizardTitle="Add New Staff Member"
      wizardIcon={UsersIcon}
      data={staffList?.results || []}
      columns={columns}
      isLoading={isLoading}
      errors={errors}
      searchFilter={searchFilterConfig}
      pagination={paginationConfig}
      onSearchAgain={handleSearchAgain}
      onAddNew={handleAddNew}
      entityName="staff member"
      emptyState={{
        icon: UsersIcon,
        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,
      }}
    />
  );
}

export default AdminStaffAddStep1PartBPage;
