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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useSearchParams } from "react-router";
import {
  useEventManager,
  useEventOrderWizardStorage,
} from "../../../../services/Services";
import {
  SelectButton,
  UIXThemeProvider,
  Badge,
  StepWizard,
  UniversalListPage,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import {
  TicketIcon,
  CalendarIcon,
  MapPinIcon,
  UserGroupIcon,
  ClockIcon,
  CalendarDaysIcon,
  AcademicCapIcon,
  UsersIcon,
  Squares2X2Icon,
  ListBulletIcon,
  MagnifyingGlassIcon,
  PlusIcon,
} 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,
  formatDate,
} from "../../../../services/Helpers/DateFormatter";

// Configuration for wizard steps - moved outside component
const WIZARD_STEPS = [
  { title: "Find Event" },
  { title: "Find Customer" },
  { title: "Order Requirements" },
  { title: "Additional Details" },
  { title: "Review & Confirm" },
];

function AdminEventOrderAddStep1ResultsPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const eventManager = useEventManager();
  const wizardStorage = useEventOrderWizardStorage();
  const { getThemeClasses } = useUIXTheme();
  const [errors, setErrors] = useState({});

  // Extract initial search parameters from URL
  const initialParams = useMemo(() => {
    const urlParams = new URLSearchParams(location.search);
    const searchQuery = urlParams.get("q") || "";
    const eventName = urlParams.get("name") || "";
    const type = urlParams.get("type") || "0";
    const status = urlParams.get("status") || "1";

    // Build search query from parameters
    const searchTerms = [searchQuery, eventName].filter(Boolean);
    const combinedSearch = searchTerms.length > 0 ? searchTerms.join(" ") : "";

    return {
      searchQuery: combinedSearch,
      type,
      status,
    };
  }, [location.search]);

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

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

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

  // Format SHSM - handles both boolean and filter number values
  const getEventSHSMLabel = useCallback((shsmValue) => {
    // Handle boolean values from backend
    if (typeof shsmValue === "boolean") {
      return shsmValue ? "Yes" : "No";
    }
    // Handle filter number values (1 = Yes, 2 = No)
    const option = EVENT_SHSM_OPTIONS.find(
      (opt) => opt.value === String(shsmValue),
    );
    return option ? option.label : "-";
  }, []);

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

  // Format event datetime for display
  const formatEventDateTime = useCallback((startDateTime, endDateTime) => {
    if (!startDateTime || !endDateTime) return "—";

    try {
      const start = new Date(startDateTime);
      const end = new Date(endDateTime);

      // Get just the date part (no time) using formatDate
      const startDate = formatDate(startDateTime, "medium");
      const startTime = start.toLocaleTimeString("en-US", {
        hour: "numeric",
        minute: "2-digit",
        hour12: true,
      });
      const endTime = end.toLocaleTimeString("en-US", {
        hour: "numeric",
        minute: "2-digit",
        hour12: true,
      });

      return { date: startDate, time: `${startTime} - ${endTime}` };
    } catch (error) {
      return { date: "—", time: "—" };
    }
  }, []);

  // Handle event selection - MUST be before renderEventCard
  const handleSelectEvent = useCallback(
    async (event) => {
      try {
        setErrors({});

        // Fetch full event details including order requirements
        const fullEventDetails = await eventManager.getEventDetail(
          event.id,
          onUnauthorized,
        );

        // Store complete event in wizard storage
        wizardStorage.setEvent(fullEventDetails);

        // Navigate to Step 2 (Customer Search)
        navigate("/admin/event-orders/add/step-2-search");
      } catch (err) {
        setErrors({
          message: "Failed to load event details. Please try again.",
        });
      }
    },
    [eventManager, onUnauthorized, wizardStorage, navigate],
  );

  // Render grid card for an event (similar to conferences)
  const renderEventCard = useCallback(
    (event) => {
      const formatted = formatEventDateTime(
        event.startDateTime,
        event.endDateTime,
      );

      return (
        <div
          key={event.id}
          className={`${getThemeClasses("bg-card")} border ${getThemeClasses("card-border")} rounded-lg shadow-sm hover:shadow-lg transition-shadow`}
        >
          <div className="p-6">
            {/* Event Name */}
            <div className="mb-4">
              <h3
                className={`text-lg font-semibold ${getThemeClasses("text-primary")} flex items-start`}
              >
                <CalendarDaysIcon
                  className={`w-6 h-6 mr-2 flex-shrink-0 mt-0.5 ${getThemeClasses("text-muted")}`}
                />
                <span>{event.eventName || "Unnamed Event"}</span>
              </h3>

              {/* Event Type Badge */}
              <div className="mt-2 ml-8">{getTypeBadge(event.type)}</div>

              {/* Partners */}
              {event.partners && (
                <div
                  className={`mt-2 ml-8 text-sm ${getThemeClasses("text-secondary")}`}
                >
                  {event.partners}
                </div>
              )}

              {/* Description */}
              {event.description && (
                <div
                  className={`mt-2 ml-8 text-sm ${getThemeClasses("text-muted")} line-clamp-2`}
                >
                  {event.description}
                </div>
              )}
            </div>

            {/* Event Details */}
            <div
              className={`space-y-2 text-base ${getThemeClasses("text-primary")} mb-4`}
            >
              {/* Date and Time */}
              {formatted !== "—" && (
                <>
                  <div className="flex items-center text-sm">
                    <CalendarIcon
                      className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                    />
                    <span>{formatted.date}</span>
                  </div>
                  <div className="flex items-center text-sm">
                    <ClockIcon
                      className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                    />
                    <span>{formatted.time}</span>
                  </div>
                </>
              )}

              {/* Location */}
              {event.location && (
                <div className="flex items-center text-sm">
                  <MapPinIcon
                    className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                  />
                  <span className="line-clamp-1">{event.location}</span>
                </div>
              )}

              {/* Attendee Capacity */}
              {event.attendeeCapacity > 0 && (
                <div className="flex items-center text-sm">
                  <UserGroupIcon
                    className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                  />
                  <span>{event.attendeeCapacity} attendees</span>
                </div>
              )}

              {/* SHSM Badge */}
              {(event.isSHSM === true || event.isSHSM === 1) && (
                <div className="flex items-center">
                  <AcademicCapIcon
                    className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                  />
                  <Badge variant="success" size="sm">
                    SHSM: {getEventSHSMLabel(event.isSHSM)}
                  </Badge>
                </div>
              )}

              {/* Facilitator Time */}
              {(event.facilitatorAM || event.facilitatorPM) && (
                <div className="flex items-center text-sm">
                  <UsersIcon
                    className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                  />
                  <span>
                    Facilitator:{" "}
                    {event.facilitatorAM && event.facilitatorPM
                      ? "AM & PM"
                      : event.facilitatorAM
                        ? "AM"
                        : "PM"}
                  </span>
                </div>
              )}
            </div>

            {/* Select Button */}
            <div className="flex gap-2">
              <SelectButton onClick={() => handleSelectEvent(event)} fullWidth>
                Select Event
              </SelectButton>
            </div>
          </div>
        </div>
      );
    },
    [
      formatEventDateTime,
      getThemeClasses,
      getTypeBadge,
      getEventSHSMLabel,
      handleSelectEvent,
    ],
  );

  // Column configuration for DataList
  const columns = useMemo(
    () => [
      {
        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) => {
          const formatted = formatEventDateTime(
            event.startDateTime,
            event.endDateTime,
          );

          if (formatted === "—") {
            return <span className="text-gray-400">—</span>;
          }

          return (
            <div className="space-y-1 text-sm">
              <div className="flex items-center">
                <CalendarIcon className="w-4 h-4 mr-2 text-gray-400 flex-shrink-0" />
                <span className="font-medium">{formatted.date}</span>
              </div>
              <div className="flex items-center">
                <ClockIcon className="w-4 h-4 mr-2 text-gray-400 flex-shrink-0" />
                <span>{formatted.time}</span>
              </div>
            </div>
          );
        },
      },
      {
        header: "Type",
        accessor: "type",
        render: (type) => getTypeBadge(type),
      },
      {
        header: "Details",
        accessor: "details",
        render: (value, event) => (
          <div className="space-y-1 text-sm">
            {event.attendeeCapacity > 0 && (
              <div className="flex items-center text-gray-600">
                <UserGroupIcon className="w-4 h-4 mr-1" />
                {event.attendeeCapacity} attendees
              </div>
            )}
            {(event.isSHSM === true || event.isSHSM === 1) && (
              <div className="flex items-center">
                <AcademicCapIcon className="w-4 h-4 mr-1" />
                <Badge variant="success" size="sm">
                  SHSM: {getEventSHSMLabel(event.isSHSM)}
                </Badge>
              </div>
            )}
            {(event.facilitatorAM || event.facilitatorPM) && (
              <div className="flex items-center text-gray-600">
                <UsersIcon className="w-4 h-4 mr-1" />
                Facilitator:{" "}
                {event.facilitatorAM && event.facilitatorPM
                  ? "AM & PM"
                  : event.facilitatorAM
                    ? "AM"
                    : "PM"}
              </div>
            )}
          </div>
        ),
      },
      {
        header: "Actions",
        align: "right",
        type: "action",
        render: (value, event) => (
          <SelectButton onClick={() => handleSelectEvent(event)}>
            Select
          </SelectButton>
        ),
      },
    ],
    [getTypeBadge, getEventSHSMLabel, formatEventDateTime, handleSelectEvent],
  ); // getThemeClasses removed - captured in closure

  // Build params function for UniversalListPage
  const buildParams = useCallback((params) => {
    const {
      pageSize = 25,
      currentCursor,
      sortBy,
      sortOrder,
      status,
      type,
      searchQuery,
    } = params || {};

    const filtersMap = new Map();
    filtersMap.set("page_size", String(pageSize));

    // Add cursor for pagination
    if (currentCursor) {
      filtersMap.set("cursor", currentCursor);
    }

    // Add sorting
    if (sortBy && sortOrder) {
      filtersMap.set("sortField", sortBy);
      filtersMap.set("sortOrder", sortOrder);
    }

    // Add filters
    if (status && status !== "0" && status !== "") {
      filtersMap.set("status", parseInt(status));
    }

    if (type && type !== "0" && type !== "") {
      filtersMap.set("type", parseInt(type));
    }

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

    return filtersMap;
  }, []);

  // Fetch data function for UniversalListPage
  // NOTE: params is already a filtersMap (Map object) built by buildParams in UniversalListPage
  const fetchData = useCallback(
    async (params, onUnauthorized, forceRefresh) => {
      return new Promise((resolve, reject) => {
        eventManager.getEventsWithFiltersMapWithCallbacks(
          params, // params is already a filtersMap, no need to call buildParams again
          (response) => {
            resolve({
              results: response.results || [],
              count: response.count || 0,
              nextCursor: response.nextCursor || "",
            });
          },
          reject,
          () => {}, // onDone callback
          onUnauthorized,
          true, // Always force refresh for search results to avoid stale cached data
        );
      });
    },
    [eventManager],
  );

  // UniversalListPage configuration
  const config = useMemo(
    () => ({
      entityName: "Event",
      entityNamePlural: "Events",
      icon: CalendarDaysIcon,
      searchIcon: MagnifyingGlassIcon,
      createIcon: PlusIcon,
      createLabel: "Add New Event",
      routes: {
        search: "/admin/event-orders/add/step-1-search",
        create: "/admin/events/add",
        detail: "/admin/events/:id",
      },
      breadcrumbItems: WIZARD_STEPS.map((step, index) => ({
        label: step.title,
        to: index === 0 ? "/admin/event-orders/add/step-1-search" : undefined,
        icon: index === 0 ? CalendarDaysIcon : undefined,
        isActive: index === 0,
      })),
      title: "Event Search Results",
      subtitle: "Select an event to create an order",
      columns,
      statusOptions: EVENT_STATUS_FILTER_OPTIONS,
      typeOptions: EVENT_TYPE_FILTER_OPTIONS,
      sortOptions: EVENT_SORT_OPTIONS.map((opt) => ({
        value: opt.value,
        label: opt.label,
      })),
      pageSizeOptions: PAGE_SIZE_OPTIONS.map((opt) => ({
        value: opt.value,
        label: opt.label,
      })),
      searchPlaceholder: "Search events by name...",
      emptyState: {
        title: "No Events Found",
        filterDescription:
          "No events match your current filters. Try adjusting your search criteria.",
        emptyDescription: "No events have been added yet.",
        actionLabel: "Add New Event",
      },
      fetchData,
      buildParams,
      renderGridItem: renderEventCard,
      // Initial values from URL parameters
      defaultSearchQuery: initialParams.searchQuery,
      defaultStatus: initialParams.status,
      defaultType: initialParams.type,
      defaultSort: "name",
      defaultSortOrder: "ASC",
      defaultPageSize: 25,
      defaultViewType: "grid",
      // Custom button labels for wizard flow
      showSearchButton: true,
      showCreateButton: true,
    }),
    [columns, fetchData, buildParams, renderEventCard, initialParams],
  );

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={1}
        title="Create Event Order"
        icon={TicketIcon}
      >
        <UniversalListPage config={config} />
      </StepWizard>
    </UIXThemeProvider>
  );
}

export default AdminEventOrderAddStep1ResultsPage;
