// File Path: monorepo/web/frontend/src/pages/Admin/Speaker/Search/ResultPage.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useSearchParams } from "react-router";
import { useSpeakerManager, useTagManager } from "../../../../services/Services";
import {
  MagnifyingGlassIcon,
  ArrowLeftIcon,
  EyeIcon,
  SpeakerWaveIcon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
  UserIcon,
  HomeIcon,
  PlusIcon,
  BuildingOffice2Icon,
} from "@heroicons/react/24/outline";
import {
  SearchResultsPage,
  ViewButton,
  Badge,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  SPEAKER_STATUS_FILTER_OPTIONS,
  SPEAKER_TYPE_OF_FILTER_OPTIONS,
  SPEAKER_SORT_OPTIONS,
  RESIDENTIAL_SPEAKER_TYPE_OF_ID,
  COMMERCIAL_SPEAKER_TYPE_OF_ID,
} from "../../../../constants/Speaker";

function AdminSpeakerSearchResultPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const speakerManager = useSpeakerManager();
  const tagManager = useTagManager();
  const { getThemeClasses } = useUIXTheme();

  // List state
  const [speakerList, setSpeakerList] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [tagOptions, setTagOptions] = 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("");
  const [type, setType] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");

  // Extract search parameters from URL
  const searchCriteria = useMemo(() => {
    const criteria = [];
    const firstName = searchParams.get("fn");
    const lastName = searchParams.get("ln");
    const email = searchParams.get("e");
    const phone = searchParams.get("p");
    const organizationName = searchParams.get("on");
    const tags = searchParams.get("tags");
    const activeOnly = searchParams.get("active");

    if (firstName) criteria.push(`First Name: ${firstName}`);
    if (lastName) criteria.push(`Last Name: ${lastName}`);
    if (email) criteria.push(`Email: ${email}`);
    if (phone) criteria.push(`Phone: ${phone}`);
    if (organizationName) criteria.push(`Organization: ${organizationName}`);
    if (tags) {
      // Map tag IDs to labels
      const tagIds = tags.split(",");
      const tagLabels = tagIds
        .map((tagId) => {
          const tag = tagOptions.find((opt) => opt.value === tagId);
          return tag ? tag.label : tagId;
        })
        .join(", ");
      criteria.push(`Tags: ${tagLabels}`);
    }
    if (activeOnly) criteria.push("Active Only");

    return criteria;
  }, [searchParams, tagOptions]);

  // Breadcrumb configuration
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Speakers",
      to: "/admin/speakers",
      icon: SpeakerWaveIcon,
    },
    {
      label: "Search",
      to: "/admin/speakers/search",
      icon: MagnifyingGlassIcon,
    },
    {
      label: "Results",
      isActive: true,
    },
  ];

  // Action buttons configuration
  const actionButtons = [
    {
      label: "New Search",
      variant: "secondary",
      icon: ArrowLeftIcon,
      onClick: () => navigate("/admin/speakers/search"),
    },
    {
      label: "Add Speaker",
      variant: "success",
      icon: PlusIcon,
      onClick: () => navigate("/admin/speakers/add"),
    },
  ];

  // Handle unauthorized access
  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
  }, []); // Run once on mount - tagManager and onUnauthorized are stable

  // 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
    const firstName = searchParams.get("fn");
    const lastName = searchParams.get("ln");
    const email = searchParams.get("e");
    const phone = searchParams.get("p");
    const organizationName = searchParams.get("on");
    const tags = searchParams.get("tags");
    const activeOnly = searchParams.get("active");

    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 (organizationName) map.set("organization_name", organizationName);
    if (tags) map.set("inTagIds", tags); // Backend expects in_tag_ids for "any of these tags"
    if (activeOnly) map.set("status", 1); // Active only

    if (searchQuery && searchQuery.trim()) {
      map.set("search", searchQuery.trim());
    }

    return map;
  }, [currentCursor, pageSize, sortBy, sortOrder, status, type, searchQuery, searchParams]);

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

      // Use the manager to fetch speakers with force refresh flag
      speakerManager.getSpeakersWithFiltersMapWithCallbacks(
        filtersMap,
        (response) => {
          setSpeakerList(response);

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

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

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

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

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

  // 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;
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Speaker",
      accessor: "firstName",
      type: "text",
      render: (value, speaker) => {
        const displayName = speaker.type === COMMERCIAL_SPEAKER_TYPE_OF_ID
          ? (speaker.organizationName || `${speaker.firstName} ${speaker.lastName}`)
          : `${speaker.firstName} ${speaker.lastName}`;
        return (
          <div className="flex items-center">
            {speaker.type === COMMERCIAL_SPEAKER_TYPE_OF_ID ? (
              <BuildingOffice2Icon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            ) : (
              <UserIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            )}
            <div>
              <div className="font-medium">{displayName}</div>
              {speaker.type === COMMERCIAL_SPEAKER_TYPE_OF_ID && speaker.organizationName && (
                <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  {speaker.firstName} {speaker.lastName}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Contact",
      accessor: "email",
      render: (email, speaker) => {
        if (!email && !speaker.phone) return "—";
        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>
            )}
            {speaker.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <a
                  href={`tel:${speaker.phone}`}
                  className={`transition-colors ${getThemeClasses('link-primary')}`}
                  onClick={(e) => e.stopPropagation()}
                >
                  {formatPhone(speaker.phone)}
                </a>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Location",
      accessor: "city",
      render: (city, speaker) => {
        if (!speaker.addressLine1 && !speaker.city && !speaker.region) return "—";
        return (
          <div className="flex items-center text-sm">
            <MapPinIcon className={`w-4 h-4 mr-1 ${getThemeClasses('text-muted')}`} />
            <div>
              {speaker.addressLine1 && <div>{speaker.addressLine1}</div>}
              {(speaker.city || speaker.region) && (
                <div>
                  {[speaker.city, speaker.region].filter(Boolean).join(", ")}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Type",
      accessor: "type",
      render: (type) => getTypeBadge(type)
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, speaker) => (
        <ViewButton
          to={`/admin/speaker/${speaker.id}`}
        >
          View
        </ViewButton>
      )
    }
  ];

  // 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("");
    setType("");
    setSearchQuery("");
    setTempSearchQuery("");
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  // Memoize search filter configuration to prevent unnecessary re-renders
  const searchFilterConfig = useMemo(() => ({
    searchTerm: searchQuery,
    tempSearchTerm: tempSearchQuery,
    onSearchTermChange: setTempSearchQuery,
    onSearch: handleSearch,
    searchPlaceholder: "Search speakers by name...",
    statusOptions: SPEAKER_STATUS_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: SPEAKER_TYPE_OF_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    typeFilter: type,
    onTypeFilterChange: handleTypeChange,
    sortOptions: SPEAKER_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: () => fetchSpeakerList(true)
  }), [searchQuery, tempSearchQuery, status, type, sortBy, sortOrder, pageSize, handleSearch, handleStatusChange, handleTypeChange, handleSortChange, handlePageSizeChange, handleClearFilters, fetchSpeakerList]);

  // Memoize pagination configuration to prevent unnecessary re-renders
  const paginationConfig = useMemo(() => ({
    currentPage: previousCursors.length + 1,
    totalCount: speakerList?.count || 0,
    hasNextPage: !!nextCursor,
    onPageChange: (direction) => {
      if (direction > previousCursors.length + 1) {
        handlePageChange("next");
      } else {
        handlePageChange("previous");
      }
    }
  }), [previousCursors.length, speakerList?.count, nextCursor, handlePageChange]);

  // Fetch speakers when filters or search params change
  useEffect(() => {
    fetchSpeakerList(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    currentCursor,
    pageSize,
    sortBy,
    sortOrder,
    status,
    type,
    searchQuery,
    searchParams, // Include searchParams to detect URL param changes (tags, etc.)
  ]);

  return (
    <SearchResultsPage
      breadcrumbItems={breadcrumbItems}
      searchCriteria={searchCriteria}
      pageTitle="Speaker Search Results"
      actionButtons={actionButtons}
      results={speakerList?.results || []}
      columns={columns}
      isLoading={isLoading}
      errors={errors}
      searchFilter={searchFilterConfig}
      pagination={paginationConfig}
      emptyState={{
        icon: SpeakerWaveIcon,
        title: "No Speakers Found",
        description: "No speakers match your search criteria. Try adjusting your search terms or create a new speaker.",
        isCreateAction: true,
      }}
    />
  );
}

export default AdminSpeakerSearchResultPage;