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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useSearchParams } from "react-router";
import { useFacilitatorManager } from "../../../../services/Services";
import {
  WizardSearchResults,
  SelectButton,
  UIXThemeProvider,
  Badge,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import {
  BriefcaseIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  FACILITATOR_STATUS_OPTIONS,
  FACILITATOR_TYPE_OPTIONS,
  FACILITATOR_SORT_OPTIONS,
} from "../../../../constants/Facilitator";

function AdminFacilitatorAddStep1ResultsPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const facilitatorManager = useFacilitatorManager();
  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 [facilitatorList, setFacilitatorList] = 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(" "));
    }
  }, [searchParams]);

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

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

    // Add search params from URL
    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");

    if (firstName) map.set("firstName", firstName);
    if (lastName) map.set("lastName", 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, 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],
  );

  // 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 facilitator status
  const getStatusBadge = (facilitatorStatus) => {
    const variantMap = {
      1: "success", // Active
      0: "secondary", // Archived
    };
    const variant = variantMap[facilitatorStatus] || "default";

    const statusLabels = {
      1: "Active",
      0: "Archived",
    };

    return (
      <Badge variant={variant} size="sm">
        {statusLabels[facilitatorStatus] || "Unknown"}
      </Badge>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Name",
      accessor: "name",
      type: "text",
      render: (value, facilitator) => {
        const displayName = facilitator.name || `${facilitator.firstName} ${facilitator.lastName}`;
        return (
          <div className="flex items-center">
            <BriefcaseIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            <div>
              <div className="font-medium">{displayName}</div>
              {facilitator.jobTitle && (
                <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  {facilitator.jobTitle}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Contact",
      accessor: "email",
      render: (email, facilitator) => {
        if (!email && !facilitator.phone) return null;
        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')}`} />
                <span>{facilitator.phone}</span>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, facilitator) => (
        <SelectButton
          onClick={() => handleSelectFacilitator(facilitator)}
        >
          Select
        </SelectButton>
      )
    }
  ];

  // Handle facilitator selection
  const handleSelectFacilitator = (facilitator) => {
    // Store selected facilitator data
    sessionStorage.setItem("FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE", JSON.stringify({
      selectedFacilitator: facilitator
    }));
    // Navigate to facilitator detail page
    navigate(`/admin/facilitator/${facilitator.id}`);
  };

  // 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, email, or phone...",
    statusOptions: FACILITATOR_STATUS_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: FACILITATOR_TYPE_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]);

  // Action handlers
  const handleSearchAgain = () => {
    navigate("/admin/facilitators/add/step-1-part-a");
  };

  const handleAddNew = () => {
    // Clear any existing facilitator creation state
    sessionStorage.removeItem("FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE");
    // Navigate directly to step 2
    navigate("/admin/facilitators/add/step-2");
  };

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

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

  return (
    <UIXThemeProvider>
      <WizardSearchResults
        wizardSteps={wizardSteps}
        currentStep={1}
        wizardTitle="Add New Facilitator"
        wizardIcon={WrenchScrewdriverIcon}
        data={facilitatorList?.results || []}
        columns={columns}
        isLoading={isLoading}
        errors={errors}
        searchFilter={searchFilterConfig}
        pagination={paginationConfig}
        entityName="facilitator"
        onSearchAgain={handleSearchAgain}
        onAddNew={handleAddNew}
        emptyState={{
          icon: UserIcon,
          title: "No Facilitators Found",
          description: "No facilitators match your search criteria. Try adjusting your search terms or create a new facilitator."
        }}
      />
    </UIXThemeProvider>
  );
}

export default AdminFacilitatorAddStep1ResultsPage;