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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useSearchParams } from "react-router";
import {
  useEventManager,
  useEventContractWizardStorage,
} from "../../../../services/Services";
import {
  WizardSearchResults,
  SelectButton,
  UIXThemeProvider,
  Badge,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import {
  TicketIcon,
  CalendarIcon,
  MapPinIcon,
  UserGroupIcon,
  TagIcon,
  ClockIcon,
  CalendarDaysIcon,
  AcademicCapIcon,
  UsersIcon,
} from "@heroicons/react/24/outline";
import { PAGE_SIZE_OPTIONS } from "../../../../constants/FieldOptions";
import {
  EVENT_TYPE_OPTIONS,
  EVENT_STATUS_OPTIONS,
  EVENT_SHSM_OPTIONS,
  EVENT_TYPE_FILTER_OPTIONS,
  EVENT_STATUS_FILTER_OPTIONS,
  EVENT_SORT_OPTIONS,
} from "../../../../constants/Event";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

function AdminEventContractAddStep1ResultsPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const eventManager = useEventManager();
  const wizardStorage = useEventContractWizardStorage();
  const { getThemeClasses } = useUIXTheme();

  // Configuration for wizard steps
  const wizardSteps = [
    { title: "Find Event" },
    { title: "Contract Details" },
    { title: "Attachments" },
    { title: "Review & Confirm" },
  ];

  // List state
  const [eventList, setEventList] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({});

  // Pagination state (offset-based for events)
  const [pageSize, setPageSize] = useState(25);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);

  // Filter state
  const [sortBy, setSortBy] = useState("start_date_time");
  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 searchQuery = urlParams.get("q") || "";
    const eventName = urlParams.get("name") || "";
    const type = urlParams.get("type") || "";
    const status = urlParams.get("status") || "1";

    // Build search query from parameters
    const searchTerms = [searchQuery, eventName].filter(Boolean);
    if (searchTerms.length > 0) {
      setSearchQuery(searchTerms.join(" "));
      setTempSearchQuery(searchTerms.join(" "));
    }
    if (type) setType(type);
    if (status) setStatus(status);
  }, [searchParams]);

  // Handle unauthorized access
  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };

  // Memoize API parameters to prevent unnecessary rebuilds
  const apiParams = useMemo(() => {
    const params = {
      page: currentPage,
      limit: pageSize,
      sortField: sortBy,
      sortOrder: sortOrder,
    };

    // Add search params from URL
    const urlParams = new URLSearchParams(location.search);
    const urlSearchQuery = urlParams.get("q");
    const eventName = urlParams.get("name");
    const urlType = urlParams.get("type");
    const urlStatus = urlParams.get("status");
    const isSHSM = urlParams.get("shsm");
    const startFrom = urlParams.get("startFrom");
    const startTo = urlParams.get("startTo");
    const dayOfWeek = urlParams.get("dow");
    const skillSets = urlParams.get("skills");
    const tags = urlParams.get("tags");
    const facilitatorTime = urlParams.get("facTime");

    if (urlSearchQuery) params.search = urlSearchQuery;
    if (eventName) params.eventName = eventName;
    if (urlType) params.type = urlType;
    if (urlStatus) params.status = urlStatus;
    if (isSHSM) params.isSHSM = isSHSM;
    if (startFrom) params.startDateGTE = startFrom;
    if (startTo) params.startDateLTE = startTo;
    if (dayOfWeek) params.dayOfWeek = dayOfWeek;
    if (skillSets)
      params.skillSetIDs = skillSets.split(",").map((id) => id.trim());
    if (tags) params.tagIDs = tags.split(",").map((id) => id.trim());
    if (facilitatorTime) params.facilitatorTime = facilitatorTime;
    if (searchQuery && searchQuery.trim()) params.search = searchQuery.trim();
    if (status !== "0") params.status = parseInt(status);
    if (type !== "0") params.type = parseInt(type);

    return params;
  }, [
    currentPage,
    pageSize,
    sortBy,
    sortOrder,
    status,
    type,
    searchQuery,
    searchParams,
  ]);

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

      // Use the manager to fetch events
      eventManager
        .getEvents(apiParams, onUnauthorized, forceRefresh)
        .then((response) => {
          setEventList(response);
          setTotalPages(Math.ceil((response.count || 0) / pageSize));
        })
        .catch((error) => {
          if (process.env.NODE_ENV === "development") {
            console.error("Error fetching event list:", error);
          }
          setErrors({ message: "Failed to load events. Please try again." });
        })
        .finally(() => {
          setIsLoading(false);
        });
    },
    [apiParams, eventManager, onUnauthorized, pageSize],
  );

  // Search handler
  const handleSearch = () => {
    setSearchQuery(tempSearchQuery);
    // Reset pagination when search changes
    setCurrentPage(1);
  };

  // Filter change handlers
  const handleSortChange = (value) => {
    const [field, order] = value.split(",");
    setSortBy(field);
    setSortOrder(order);
    // Reset pagination when sort changes
    setCurrentPage(1);
  };

  const handleStatusChange = (value) => {
    setStatus(value);
    // Reset pagination when status changes
    setCurrentPage(1);
  };

  const handleTypeChange = (value) => {
    setType(value);
    // Reset pagination when type changes
    setCurrentPage(1);
  };

  const handlePageSizeChange = (value) => {
    setPageSize(value);
    // Reset pagination when page size changes
    setCurrentPage(1);
  };

  // Clear filters
  const handleClearFilters = () => {
    setSortBy("start_date_time");
    setSortOrder("ASC");
    setStatus("1");
    setType("0");
    setSearchQuery("");
    setTempSearchQuery("");
    setCurrentPage(1);
  };

  // Format event type
  const getEventTypeLabel = (typeValue) => {
    const option = EVENT_TYPE_OPTIONS.find(
      (opt) => opt.value === String(typeValue),
    );
    return option ? option.label : "Unknown";
  };

  // Format event status
  const getEventStatusLabel = (statusValue) => {
    const option = EVENT_STATUS_OPTIONS.find(
      (opt) => opt.value === String(statusValue),
    );
    return option ? option.label : "Unknown";
  };

  // Get badge component for event status
  const getStatusBadge = (eventStatus) => {
    const variantMap = {
      1: "success", // Active
      2: "secondary", // Archived
    };
    const variant = variantMap[eventStatus] || "default";

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

  // Get badge component for event type
  const getTypeBadge = (eventType) => {
    return (
      <Badge variant="primary" size="sm">
        {getEventTypeLabel(eventType)}
      </Badge>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Event",
      accessor: "eventName",
      type: "text",
      render: (value, event) => {
        return (
          <div>
            <div className="font-medium">{event.eventName}</div>
            {event.partners && (
              <div className={`text-sm ${getThemeClasses("text-secondary")}`}>
                {event.partners}
              </div>
            )}
            {event.description && (
              <div
                className={`text-sm ${getThemeClasses("text-muted")} line-clamp-2`}
              >
                {event.description}
              </div>
            )}
          </div>
        );
      },
    },
    {
      header: "Date & Time",
      accessor: "startDateTime",
      render: (startDateTime, event) => {
        return (
          <div className="space-y-1 text-sm">
            {startDateTime && (
              <div className="flex items-center">
                <CalendarIcon
                  className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`}
                />
                {formatDateForDisplay(startDateTime)}
              </div>
            )}
            {event.startTime && (
              <div className="flex items-center">
                <ClockIcon
                  className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`}
                />
                {event.startTime}
              </div>
            )}
          </div>
        );
      },
    },
    {
      header: "Type",
      accessor: "type",
      render: (type) => getTypeBadge(type),
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, event) => (
        <SelectButton onClick={() => handleSelectEvent(event)}>
          Select
        </SelectButton>
      ),
    },
  ];

  // Handle event selection
  const handleSelectEvent = (event) => {
    // Store selected event data
    wizardStorage.setEvent(event);
    // Navigate to step 3 (Attachments)
    navigate("/admin/event-contracts/add/step-3");
  };

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

  // Memoize pagination configuration to prevent unnecessary re-renders
  const paginationConfig = useMemo(
    () => ({
      currentPage,
      totalCount: eventList?.count || 0,
      totalPages,
      hasNextPage: currentPage < totalPages,
      onPageChange: (page) => setCurrentPage(page),
    }),
    [currentPage, eventList?.count, totalPages],
  );

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

  const handleAddNew = () => {
    // Navigate to event creation
    navigate("/admin/events/add");
  };

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

  // Effect for filter changes and pagination
  useEffect(() => {
    if (searchQuery || currentPage > 1 || status !== "1" || type !== "0") {
      fetchEventList(true);
    }
  }, [currentPage, pageSize, sortBy, sortOrder, status, type, searchQuery]);

  return (
    <UIXThemeProvider>
      <WizardSearchResults
        wizardSteps={wizardSteps}
        currentStep={1}
        wizardTitle="Create Event Contract"
        wizardIcon={TicketIcon}
        data={eventList?.results || []}
        columns={columns}
        isLoading={isLoading}
        errors={errors}
        searchFilter={searchFilterConfig}
        pagination={paginationConfig}
        entityName="event"
        onSearchAgain={handleSearchAgain}
        onAddNew={handleAddNew}
        emptyState={{
          icon: CalendarDaysIcon,
          title: "No Events Found",
          description:
            "No events match your search criteria. Try adjusting your search terms or create a new event.",
        }}
      />
    </UIXThemeProvider>
  );
}

export default AdminEventContractAddStep1ResultsPage;
