// File Path: monorepo/web/frontend/src/pages/Admin/Division/Add/Step1SearchResultsPage.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useLocation } from "react-router";
import {
  useAuthManager,
  useDivisionManager,
  useDivisionWizardStorage,
} from "../../../../services/Services";
import {
  BuildingOffice2Icon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
} from "@heroicons/react/24/outline";
import {
  WizardSearchResults,
  SelectButton,
  UIXThemeProvider,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import { PAGE_SIZE_OPTIONS } from "../../../../constants/FieldOptions";
import {
  DIVISION_STATUS_OPTIONS,
  DIVISION_TYPE_OPTIONS,
  DIVISION_TYPE_LABELS,
  DIVISION_SORT_OPTIONS,
} from "../../../../constants/Division";

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

function AdminDivisionAddStep1SearchResultsPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const authManager = useAuthManager();
  const divisionManager = useDivisionManager();
  const wizardStorage = useDivisionWizardStorage();
  const { getThemeClasses } = useUIXTheme();

  // List state
  const [divisionList, setDivisionList] = 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("name");
  const [sortOrder, setSortOrder] = useState("ASC");
  const [status, setStatus] = useState("1"); // Default to active
  const [type, setType] = useState(""); // All types
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");

  // SECURITY: Authentication check on mount
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Extract search parameters from URL
  useEffect(() => {
    const urlParams = new URLSearchParams(location.search);
    const divisionName = urlParams.get("dn") || "";
    const contactName = urlParams.get("cn") || "";
    const email = urlParams.get("e") || "";
    const phone = urlParams.get("p") || "";

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

  // PERFORMANCE: Memoize callback functions to prevent instability
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  const onFetchSuccess = useCallback((response) => {
    setDivisionList(response);

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

  const onFetchError = useCallback((error) => {
    setErrors(error);
  }, []);

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

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

      // Build params object for the API
      const params = {};
      params.limit = pageSize;

      // Add cursor for pagination
      if (currentCursor) {
        params.cursor = currentCursor;
      }

      // Add sorting
      if (sortBy && sortOrder) {
        params.sortBy = sortBy;
        params.sortOrder = sortOrder;
      }

      // Add filters
      if (status !== "") {
        params.status = parseInt(status);
      }

      if (type !== "") {
        params.type = type;
      }

      if (searchQuery && searchQuery.trim()) {
        params.search = searchQuery.trim();
      }

      // Use the manager to fetch divisions with force refresh flag
      divisionManager.getDivisionsWithCallbacks(
        params,
        onFetchSuccess,
        onFetchError,
        onFetchDone,
        onUnauthorized,
        forceRefresh,
      );
    },
    [currentCursor, pageSize, sortBy, sortOrder, status, type, searchQuery, divisionManager, onFetchSuccess, onFetchError, onFetchDone, onUnauthorized],
  );

  // Pagination handlers - memoized
  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]);

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

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

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

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

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

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

  // Get badge component for division type - memoized
  const getTypeBadge = useCallback((divisionType) => {
    const colorMap = {
      sales: getThemeClasses("badge-primary"),
      marketing: getThemeClasses("badge-secondary"),
      support: getThemeClasses("badge-accent"),
      operations: getThemeClasses("badge-success"),
    };
    const colorClass =
      colorMap[divisionType] || getThemeClasses("badge-neutral");

    return (
      <span
        className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${colorClass}`}
      >
        {DIVISION_TYPE_LABELS[divisionType] || "Unknown"}
      </span>
    );
  }, [getThemeClasses]);

  // Handle division selection - memoized
  const handleSelectDivision = useCallback((division) => {
    // Store selected division data
    wizardStorage.saveStepData("step1Data", { selectedDivision: division });
    // Navigate to division detail page
    navigate(`/admin/division/${division.id}`);
  }, [wizardStorage, navigate]);

  // Column configuration for DataList - memoized
  const columns = useMemo(() => [
    {
      header: "Division",
      accessor: "name",
      type: "text",
      render: (value, division) => {
        const displayName = division.name || division.divisionName;
        return displayName;
      },
    },
    {
      header: "Location",
      accessor: "address",
      render: (address, division) => {
        if (!division.addressLine1) return null;
        return (
          <span className="flex items-center">
            <MapPinIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
            <div className="text-sm">
              <div>{division.addressLine1}</div>
              <div className={getThemeClasses('text-secondary')}>
                {division.city}, {division.region}
              </div>
            </div>
          </span>
        );
      },
    },
    {
      header: "Contact",
      accessor: "contact",
      render: (contact, division) => {
        return (
          <div className="space-y-1">
            {division.email && (
              <div className="flex items-center text-sm">
                <EnvelopeIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>{division.email}</span>
              </div>
            )}
            {division.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>{division.phone}</span>
              </div>
            )}
          </div>
        );
      },
    },
    {
      header: "Type",
      accessor: "type",
      render: (type) => getTypeBadge(type),
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, division) => (
        <SelectButton onClick={() => handleSelectDivision(division)}>
          Select
        </SelectButton>
      ),
    },
  ], [getTypeBadge, handleSelectDivision]);

  // Search filter configuration - memoized
  const searchFilterConfig = useMemo(() => ({
    searchTerm: searchQuery,
    tempSearchTerm: tempSearchQuery,
    onSearchTermChange: setTempSearchQuery,
    onSearch: handleSearch,
    searchPlaceholder: "Search divisions by name, contact, email, or phone...",
    statusOptions:
      DIVISION_STATUS_OPTIONS?.map((opt) => ({
        value: opt.value.toString(),
        label: opt.label,
      })) || [],
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions:
      DIVISION_TYPE_OPTIONS?.map((opt) => ({
        value: opt.value.toString(),
        label: opt.label,
      })) || [],
    typeFilter: type,
    onTypeFilterChange: handleTypeChange,
    sortOptions: DIVISION_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: () => fetchDivisionList(true),
  }), [searchQuery, tempSearchQuery, status, type, sortBy, sortOrder, pageSize, handleSearch, handleStatusChange, handleTypeChange, handleSortChange, handlePageSizeChange, handleClearFilters, fetchDivisionList]);

  // Pagination configuration (cursor-based) - memoized
  const paginationConfig = useMemo(() => ({
    currentPage: previousCursors.length + 1,
    totalCount: divisionList?.count || 0,
    hasNextPage: !!nextCursor,
    onPageChange: (direction) => {
      if (direction > previousCursors.length + 1) {
        handlePageChange("next");
      } else {
        handlePageChange("previous");
      }
    },
  }), [previousCursors.length, divisionList?.count, nextCursor, handlePageChange]);

  // Action handlers - memoized
  const handleSearchAgain = useCallback(() => {
    navigate("/admin/divisions/add/step-1-search");
  }, [navigate]);

  const handleAddNew = useCallback(() => {
    // Ensure step1Data exists when proceeding to step 2
    const existingStep1Data = wizardStorage.getStepData("step1Data");
    if (!existingStep1Data) {
      // Create a default step1Data indicating search was completed
      const defaultStep1Data = {
        searchCompleted: true,
        fromResults: true,
        timestamp: new Date().toISOString(),
      };
      wizardStorage.saveStepData("step1Data", defaultStep1Data);
    }

    // Navigate to step 2
    navigate("/admin/divisions/add/step-2");
  }, [wizardStorage, navigate]);

  // PERFORMANCE: Initial load effect - use fetchDivisionList to avoid code duplication
  useEffect(() => {
    fetchDivisionList(true);
  }, [fetchDivisionList]);

  return (
    <UIXThemeProvider>
      <WizardSearchResults
        wizardSteps={WIZARD_STEPS}
        currentStep={1}
        wizardTitle="Add New Division"
        wizardIcon={BuildingOffice2Icon}
        data={divisionList?.results || []}
        columns={columns}
        isLoading={isLoading}
        errors={errors}
        searchFilter={searchFilterConfig}
        pagination={paginationConfig}
        entityName="division"
        onSearchAgain={handleSearchAgain}
        onAddNew={handleAddNew}
      />
    </UIXThemeProvider>
  );
}

export default AdminDivisionAddStep1SearchResultsPage;
