// File Path: monorepo/web/frontend/src/pages/Admin/Organization/Search/ResultsPage.jsx
import React, { useState, useEffect, useCallback } from "react";
import { Link, useNavigate, useSearchParams } from "react-router";
import { useOrganizationManager, useTagManager } from "../../../../services/Services";
import {
  MagnifyingGlassIcon,
  BuildingOffice2Icon,
  ArrowLeftIcon,
  PhoneIcon,
  EnvelopeIcon,
  ArchiveBoxIcon,
  EyeIcon,
  CheckCircleIcon,
  BuildingOfficeIcon,
  HomeIcon,
  ChevronRightIcon,
  MapPinIcon,
} from "@heroicons/react/24/outline";
import {
  SearchResultsPage,
  ViewButton,
  useUIXTheme,
} from "../../../../components/UIX";

// Organization type filter options
const ORGANIZATION_TYPE_FILTER_OPTIONS = [
  { value: "", label: "All Types" },
  { value: "educational", label: "Educational" },
  { value: "corporate", label: "Corporate" },
  { value: "non-profit", label: "Non-Profit" },
  { value: "government", label: "Government" },
];

// Organization status filter options
const ORGANIZATION_STATUS_FILTER_OPTIONS = [
  { value: "", label: "All Status" },
  { value: "1", label: "Active" },
  { value: "2", label: "Archived" },
];

// Organization sort options
const ORGANIZATION_SORT_OPTIONS = [
  { value: "name,ASC", label: "Name (A-Z)" },
  { value: "name,DESC", label: "Name (Z-A)" },
  { value: "created_at,DESC", label: "Recently Created" },
  { value: "created_at,ASC", label: "Oldest Created" },
];

// Organization type mapping
const ORGANIZATION_TYPE_MAP = {
  educational: "Educational",
  corporate: "Corporate",
  "non-profit": "Non-Profit",
  government: "Government",
};

// Page size options
const PAGE_SIZE_OPTIONS = [10, 25, 50, 100];

function AdminOrganizationSearchResultPage() {
  const navigate = useNavigate();
  const organizationManager = useOrganizationManager();
  const tagManager = useTagManager();
  const [tagOptions, setTagOptions] = useState([]);
  const [searchParams] = useSearchParams();
  const { getThemeClasses } = useUIXTheme();

  // Extract search parameters from URL
  const organizationName = searchParams.get("name") || "";
  const contactEmail = searchParams.get("email") || "";
  const contactPhone = searchParams.get("phone") || "";
  const city = searchParams.get("city") || "";
  const isActive = searchParams.get("active") === "1";

  // List state
  const [organizationList, setOrganizationList] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [successMessage, setSuccessMessage] = useState("");

  // Search filter state
  const [searchTerm, setSearchTerm] = useState("");
  const [tempSearchTerm, setTempSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState(isActive ? "1" : "");
  const [typeFilter, setTypeFilter] = useState("");
  const [sortValue, setSortValue] = useState("name,ASC");
  const [pageSize, setPageSize] = useState(50);

  // Pagination state
  const [previousCursors, setPreviousCursors] = useState([]);
  const [currentCursor, setCurrentCursor] = useState("");
  const [nextCursor, setNextCursor] = useState("");

  // Fetch organization list based on search criteria
  const fetchOrganizationList = useCallback(() => {
    // Fetching search results

    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 (sortValue) {
      const [sortField, sortOrder] = sortValue.split(",");
      params.sortBy = sortField;
      params.sortOrder = sortOrder;
    }

    // Add search criteria from URL
    if (organizationName) params.name = organizationName;
    if (contactEmail) params.email = contactEmail;
    if (contactPhone) params.phone = contactPhone;
    if (city) params.city = city;

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

    if (typeFilter) {
      params.type = typeFilter;
    }

    // API call with params

    // Use the manager to fetch organizations with force refresh
    organizationManager.getOrganizationsWithCallbacks(
      params,
      onFetchSuccess,
      onFetchError,
      onFetchDone,
      onUnauthorized,
      true, // Force refresh to bypass cache
    );
  }, [
    organizationName,
    contactEmail,
    contactPhone,
    city,
    currentCursor,
    pageSize,
    sortValue,
    statusFilter,
    typeFilter,
  ]);

  const onFetchSuccess = (response) => {
    // Search results fetched successfully
    setOrganizationList(response);

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

  const onFetchError = (error) => {
    // console.error("Error fetching search results:", error);
    setErrors(error);
    window.scrollTo(0, 0);
  };

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

  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };
  // Fetch tag options on mount for label mapping
  useEffect(() => {
    const fetchTagOptions = async () => {
      try {
        const options = await tagManager.getTagSelectOptions(onUnauthorized, true);
        setTagOptions(options || []);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Error fetching tag options:", error);
        }
        setTagOptions([]);
      }
    };
    fetchTagOptions();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Search and filter handlers
  const handleSearchTermChange = (value) => {
    setTempSearchTerm(value);
  };

  const handleSearch = () => {
    setSearchTerm(tempSearchTerm);
    setPreviousCursors([]);
    setCurrentCursor("");
  };

  const handleStatusFilterChange = (value) => {
    setStatusFilter(value);
    setPreviousCursors([]);
    setCurrentCursor("");
  };

  const handleTypeFilterChange = (value) => {
    setTypeFilter(value);
    setPreviousCursors([]);
    setCurrentCursor("");
  };

  const handleSortChange = (value) => {
    setSortValue(value);
    setPreviousCursors([]);
    setCurrentCursor("");
  };

  const handlePageSizeChange = (value) => {
    setPageSize(value);
    setPreviousCursors([]);
    setCurrentCursor("");
  };

  const handleClearFilters = () => {
    setSearchTerm("");
    setTempSearchTerm("");
    setStatusFilter("");
    setTypeFilter("");
    setSortValue("name,ASC");
    setPageSize(50);
    setPreviousCursors([]);
    setCurrentCursor("");
  };

  const handleRefresh = () => {
    fetchOrganizationList();
  };

  // Pagination handlers
  const handlePageChange = (direction) => {
    if (direction === 1 && nextCursor) {
      // Next page
      const newPreviousCursors = [...previousCursors];
      newPreviousCursors.push(currentCursor);
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(nextCursor);
    } else if (direction === -1 && previousCursors.length > 0) {
      // Previous page
      const newPreviousCursors = [...previousCursors];
      const previousCursor = newPreviousCursors.pop();
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(previousCursor);
    }
  };

  // Format phone number
  const formatPhone = (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;
  };

  // Get type badge
  const getTypeBadge = (typeValue) => {
    // Map numeric and string values to labels
    const typeMap = {
      1: "Educational",
      2: "Corporate",
      3: "Non-Profit",
      4: "Government",
      "educational": "Educational",
      "corporate": "Corporate",
      "non-profit": "Non-Profit",
      "government": "Government",
    };

    const typeLabel = typeMap[typeValue] || "Unknown";

    return (
      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800`}>
        {typeLabel}
      </span>
    );
  };

  // Build search criteria display
  const searchCriteria = [];
  if (organizationName) searchCriteria.push(`Organization Name: ${organizationName}`);
  if (contactEmail) searchCriteria.push(`Contact Email: ${contactEmail}`);
  if (contactPhone) searchCriteria.push(`Contact Phone: ${contactPhone}`);
  if (city) searchCriteria.push(`City: ${city}`);
  searchCriteria.push(`Status: ${isActive ? "Active Only" : "All"}`);

  // Calculate pagination
  const currentPage = previousCursors.length + 1;
  const totalCount = organizationList?.count || 0;
  const hasNextPage = !!nextCursor;

  // Define columns for DataList
  const columns = [
    {
      header: "Organization",
      accessor: "organizationShortName",
      type: "text",
      render: (value, organization) => {
        const shortName = organization.organizationShortName || organization.name || "Unnamed Organization";
        const longName = organization.organizationName || organization.name;
        return (
          <div>
            <div className="font-medium">{shortName}</div>
            {longName && longName !== shortName && (
              <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                {longName}
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Contact",
      accessor: "contacts",
      render: (contacts) => {
        if (!contacts || !Array.isArray(contacts) || contacts.length === 0) {
          return "—";
        }
        const firstContact = contacts[0];
        const contactName = `${firstContact.firstName || ''} ${firstContact.lastName || ''}`.trim();
        return contactName || "—";
      }
    },
    {
      header: "Type",
      accessor: "organizationType",
      render: (type, organization) => getTypeBadge(type || organization.type)
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, organization) => (
        <ViewButton
          onClick={() => navigate(`/admin/organization/${organization.id}`)}
        >
          View
        </ViewButton>
      )
    }
  ];

  // Effect to fetch data when component mounts or filters change
  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 (sortValue) {
      const [sortField, sortOrder] = sortValue.split(",");
      params.sortBy = sortField;
      params.sortOrder = sortOrder;
    }

    // Add search criteria from URL
    if (organizationName) params.name = organizationName;
    if (contactEmail) params.email = contactEmail;
    if (contactPhone) params.phone = contactPhone;
    if (city) params.city = city;

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

    if (typeFilter) {
      params.type = typeFilter;
    }

    // Use the manager to fetch organizations with force refresh
    organizationManager.getOrganizationsWithCallbacks(
      params,
      onFetchSuccess,
      onFetchError,
      onFetchDone,
      onUnauthorized,
      true, // Force refresh to bypass cache
    );
  }, [
    organizationName,
    contactEmail,
    contactPhone,
    city,
    statusFilter,
    typeFilter,
    sortValue,
    pageSize,
    currentCursor,
  ]);

  // Configure breadcrumb items
  const breadcrumbItems = [
    {
      label: 'Dashboard',
      to: '/admin/dashboard',
      icon: HomeIcon
    },
    {
      label: 'Organizations',
      to: '/admin/organizations',
      icon: BuildingOffice2Icon
    },
    {
      label: 'Search',
      to: '/admin/organizations/search',
      icon: MagnifyingGlassIcon
    },
    {
      label: 'Results',
      icon: MagnifyingGlassIcon,
      isActive: true
    }
  ];

  // Configure action buttons
  const actionButtons = [
    {
      variant: "secondary",
      onClick: () => navigate('/admin/organizations/search'),
      icon: ArrowLeftIcon,
      label: "Back to Search"
    },
    {
      variant: "outline",
      onClick: () => navigate('/admin/organizations'),
      label: "Back to Organizations"
    }
  ];

  return (
    <SearchResultsPage
      breadcrumbItems={breadcrumbItems}
      searchCriteria={searchCriteria}
      pageTitle="Organization Search Results"
      actionButtons={actionButtons}
      results={organizationList?.results || []}
      columns={columns}
      isLoading={isLoading}
      errors={errors}
      successMessage={successMessage}
      onSuccessMessageClose={() => setSuccessMessage('')}
      searchFilter={{
        searchTerm,
        tempSearchTerm,
        onSearchTermChange: handleSearchTermChange,
        onSearch: handleSearch,
        searchPlaceholder: "Search organizations...",
        statusOptions: ORGANIZATION_STATUS_FILTER_OPTIONS,
        statusFilter,
        onStatusFilterChange: handleStatusFilterChange,
        typeOptions: ORGANIZATION_TYPE_FILTER_OPTIONS,
        typeFilter,
        onTypeFilterChange: handleTypeFilterChange,
        sortOptions: ORGANIZATION_SORT_OPTIONS,
        sortValue,
        onSortChange: handleSortChange,
        pageSizeOptions: PAGE_SIZE_OPTIONS,
        pageSize,
        onPageSizeChange: handlePageSizeChange,
        onClearFilters: handleClearFilters,
        onRefresh: handleRefresh,
      }}
      pagination={{
        currentPage,
        totalCount,
        hasNextPage,
        onPageChange: handlePageChange,
      }}
      emptyState={{
        icon: BuildingOffice2Icon,
        title: "No Organizations Found",
        description: "No organizations match your search criteria. Try adjusting your search terms or filters.",
        actionLabel: "Try New Search",
        onActionClick: () => navigate('/admin/organizations/search'),
        showAction: true,
        // Note: isCreateAction defaults to false, which is correct here since this is a "try again" action, not a create action
      }}
    />
  );
}

export default AdminOrganizationSearchResultPage;