// monorepo/web/frontend/src/pages/Admin/Organization/Add/Step1SearchResultsPage.jsx

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate, useLocation } from "react-router";
import { useOrganizationManager, useOrganizationWizardStorage } from "../../../../services/Services";
import {
  BuildingOffice2Icon,
  PlusIcon,
  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 {
  ORGANIZATION_STATUS_OPTIONS,
  ORGANIZATION_TYPE_OPTIONS,
  ORGANIZATION_TYPE_MAP,
  ORGANIZATION_SORT_OPTIONS,
} from "../../../../constants/Organization";

function AdminOrganizationAddStep1SearchResultsPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const organizationManager = useOrganizationManager();
  const wizardStorage = useOrganizationWizardStorage();
  const { getThemeClasses } = useUIXTheme();

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

  // List state
  const [organizationList, setOrganizationList] = 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("");

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

    // Build search query from parameters
    const searchTerms = [organizationName, contactName, 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");
  };

  // Fetch organization list with useCallback to prevent infinite loops
  const fetchOrganizationList = 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 organizations with force refresh flag
      organizationManager.getOrganizationsWithCallbacks(
        params,
        onFetchSuccess,
        onFetchError,
        onFetchDone,
        onUnauthorized,
        forceRefresh,
      );
    },
    [currentCursor, pageSize, sortBy, sortOrder, status, type, searchQuery, organizationManager],
  );

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

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

  const onFetchError = (error) => {
    // console.error("Error fetching organization 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("name");
    setSortOrder("ASC");
    setStatus("1");
    setType("");
    setSearchQuery("");
    setTempSearchQuery("");
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  // Get badge component for organization type
  const getTypeBadge = (organizationType) => {
    const colorMap = {
      educational: getThemeClasses('badge-primary'),
      corporate: getThemeClasses('badge-secondary'),
      "non-profit": getThemeClasses('badge-accent'),
      government: getThemeClasses('badge-success'),
    };
    const colorClass = colorMap[organizationType] || getThemeClasses('badge-neutral');

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

  // Column configuration for DataList
  const columns = [
    {
      header: "Organization",
      accessor: "name",
      type: "text",
      render: (value, organization) => {
        const displayName = organization.name;
        return displayName;
      }
    },
    {
      header: "Location",
      accessor: "address",
      render: (address, organization) => {
        if (!organization.addressLine1) return null;
        return (
          <span className="flex items-center">
            <MapPinIcon className="w-4 h-4 mr-2 text-gray-400" />
            <div className="text-sm">
              <div>{organization.addressLine1}</div>
              <div className="text-gray-500">
                {organization.city}, {organization.region}
              </div>
            </div>
          </span>
        );
      }
    },
    {
      header: "Contact",
      accessor: "contact",
      render: (contact, organization) => {
        return (
          <div className="space-y-1">
            {organization.email && (
              <div className="flex items-center text-sm">
                <EnvelopeIcon className="w-4 h-4 mr-2 text-gray-400" />
                <span>{organization.email}</span>
              </div>
            )}
            {organization.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className="w-4 h-4 mr-2 text-gray-400" />
                <span>{organization.phone}</span>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Type",
      accessor: "type",
      render: (type) => getTypeBadge(type)
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, organization) => (
        <SelectButton
          onClick={() => handleSelectOrganization(organization)}
        >
          Select
        </SelectButton>
      )
    }
  ];

  // Handle organization selection
  const handleSelectOrganization = (organization) => {
    // Store selected organization data
    wizardStorage.saveStepData("step1Data", { selectedOrganization: organization });
    // Navigate to organization detail page
    navigate(`/admin/organization/${organization.id}`);
  };

  // Search filter configuration
  const searchFilterConfig = {
    searchTerm: searchQuery,
    tempSearchTerm: tempSearchQuery,
    onSearchTermChange: setTempSearchQuery,
    onSearch: handleSearch,
    searchPlaceholder: "Search organizations by name, contact, email, or phone...",
    statusOptions: ORGANIZATION_STATUS_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: ORGANIZATION_TYPE_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    typeFilter: type,
    onTypeFilterChange: handleTypeChange,
    sortOptions: ORGANIZATION_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: () => fetchOrganizationList(true)
  };

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

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

  const handleAddNew = () => {
    // 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/organizations/add/step-2");
  };

  // Initial load effect
  useEffect(() => {
    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 organizations with force refresh flag
    organizationManager.getOrganizationsWithCallbacks(
      params,
      onFetchSuccess,
      onFetchError,
      onFetchDone,
      onUnauthorized,
      true,
    );
  }, [currentCursor, pageSize, sortBy, sortOrder, status, type, searchQuery]);

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

export default AdminOrganizationAddStep1SearchResultsPage;