// File Path: monorepo/web/frontend/src/pages/Admin/Event/Virtual/List/Page.jsx

import React, { useCallback } from "react";
import {
  ComputerDesktopIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  HomeIcon,
  ClockIcon,
  UserGroupIcon,
  CalendarIcon,
  CalendarDaysIcon,
} from "@heroicons/react/24/outline";
import {
  UniversalListPage,
  ViewButton,
  Badge,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../../constants/FieldOptions";
import {
  EVENT_TYPE_VIRTUAL,
  EVENT_STATUS_ACTIVE,
  EVENT_STATUS_ARCHIVED,
  EVENT_STATUS_CLOSED,
  EVENT_STATUS_MAP,
} from "../../../../../constants/Event";
import { useEventManager } from "../../../../../services/Services";
import { formatDateForDisplay } from "../../../../../services/Helpers/DateFormatter";

function AdminEventVirtualListPage() {
  const eventManager = useEventManager();
  const { getThemeClasses } = useUIXTheme();

  // Get badge component for event status - MEMOIZED to prevent re-renders
  const getStatusBadge = useCallback((status) => {
    const variantMap = {
      [EVENT_STATUS_ACTIVE]: "success",
      [EVENT_STATUS_ARCHIVED]: "secondary",
      [EVENT_STATUS_CLOSED]: "danger",
    };
    const variant = variantMap[status] || "default";

    return (
      <Badge variant={variant} size="sm">
        {EVENT_STATUS_MAP[status] || "Unknown"}
      </Badge>
    );
  }, []);

  // Build params function for the API - MEMOIZED to prevent infinite loops
  const buildParams = useCallback((params) => {
    const {
      pageSize = 25,
      currentCursor,
      sortBy,
      sortOrder,
      status,
      type,
      searchQuery,
    } = params || {};

    const filtersMap = new Map();
    filtersMap.set("page_size", String(pageSize));
    filtersMap.set("type", EVENT_TYPE_VIRTUAL); // Always filter for Virtual events

    // 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 !== "") {
      filtersMap.set("status", parseInt(status));
    }

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

    return filtersMap;
  }, []);

  // Fetch data function - MEMOIZED to prevent infinite loops
  // NOTE: UniversalListPage already calls buildParams and passes the filtersMap
  // So params here is actually a Map object (filtersMap), not a plain object
  const fetchData = useCallback(async (filtersMap, onUnauthorized, forceRefresh) => {
    return new Promise((resolve, reject) => {
      eventManager.getEventsWithFiltersMapWithCallbacks(
        filtersMap,
        (response) => {
          resolve({
            results: response.results || [],
            count: response.count || 0,
            nextCursor: response.nextCursor || ""
          });
        },
        reject,
        () => {}, // onDone callback
        onUnauthorized,
        forceRefresh,
      );
    });
  }, [eventManager]);

  // Custom grid item renderer
  const renderGridItem = (event, navigate) => {
    return (
      <div
        key={event.id}
        className={`${getThemeClasses('bg-card')} border ${getThemeClasses('card-border')} rounded-lg shadow-sm hover:shadow-lg transition-shadow cursor-pointer`}
        onClick={() => navigate(`/admin/events/virtual/${event.id}`)}
      >
        <div className="p-6">
          <div className="mb-4">
            <h3 className={`text-lg font-semibold ${getThemeClasses('text-primary')} flex items-start`}>
              <ComputerDesktopIcon className={`w-6 h-6 mr-2 flex-shrink-0 mt-0.5 ${getThemeClasses('text-muted')}`} />
              <span>
                {event.eventName || event.name || "Unnamed Event"}
              </span>
            </h3>
            <div className="flex items-center gap-2 mt-2 ml-8">
              {getStatusBadge(event.status)}
            </div>
          </div>

          <div className={`space-y-2 text-base ${getThemeClasses('text-primary')} mb-4`}>
            {event.startDate && (
              <div className="flex items-center text-sm">
                <CalendarIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>{formatDateForDisplay(event.startDate)}</span>
              </div>
            )}
            {event.maxAttendees && (
              <div className="flex items-center text-sm">
                <UserGroupIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>Max Attendees: {event.maxAttendees}</span>
              </div>
            )}
            {event.duration && (
              <div className="flex items-center text-sm">
                <ClockIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>Duration: {event.duration}</span>
              </div>
            )}
          </div>

          {/* Action buttons */}
          <div className="flex gap-2">
            <ViewButton
              to={`/admin/events/virtual/${event.id}`}
              text="View Details"
              fullWidth={true}
            />
          </div>
        </div>
      </div>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Event Name",
      accessor: "name",
      type: "link",
      linkPath: "/admin/events/virtual/:eventId",
      render: (value, event) => (
        <div className="flex items-center">
          <ComputerDesktopIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
          <span>{event.eventName || event.name || "Unnamed Event"}</span>
        </div>
      )
    },
    {
      header: "Date & Duration",
      accessor: "startDate",
      render: (startDate, event) => {
        if (!startDate && !event.duration) return null;
        return (
          <div className="space-y-1">
            {startDate && (
              <div className="flex items-center text-sm">
                <CalendarIcon className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`} />
                <span>{formatDateForDisplay(startDate)}</span>
              </div>
            )}
            {event.duration && (
              <div className="flex items-center text-sm">
                <ClockIcon className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`} />
                <span>{event.duration}</span>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Attendees",
      accessor: "maxAttendees",
      render: (maxAttendees) => {
        if (!maxAttendees) return null;
        return (
          <div className="flex items-center text-sm">
            <UserGroupIcon className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`} />
            <span>Max: {maxAttendees}</span>
          </div>
        );
      }
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
    {
      header: "Actions",
      align: "right",
      render: (value, event) => (
        <ViewButton
          to={`/admin/events/virtual/${event.id}`}
          text="View Event"
        />
      )
    }
  ];

  // Status filter options
  const statusOptions = [
    { value: "", label: "All Statuses" },
    { value: String(EVENT_STATUS_ACTIVE), label: EVENT_STATUS_MAP[EVENT_STATUS_ACTIVE] },
    { value: String(EVENT_STATUS_ARCHIVED), label: EVENT_STATUS_MAP[EVENT_STATUS_ARCHIVED] },
    { value: String(EVENT_STATUS_CLOSED), label: EVENT_STATUS_MAP[EVENT_STATUS_CLOSED] },
  ];

  // Sort options
  const sortOptions = [
    { value: "name,ASC", label: "Name (A → Z)" },
    { value: "name,DESC", label: "Name (Z → A)" },
    { value: "startDate,DESC", label: "Start Date (Newest → Oldest)" },
    { value: "startDate,ASC", label: "Start Date (Oldest → Newest)" },
    { value: "createdAt,DESC", label: "Created Date (Newest → Oldest)" },
    { value: "createdAt,ASC", label: "Created Date (Oldest → Newest)" },
  ];

  // UniversalListPage configuration
  const config = {
    entityName: "Virtual Event",
    entityNamePlural: "Virtual Events",
    icon: ComputerDesktopIcon,
    searchIcon: MagnifyingGlassIcon,
    createIcon: PlusIcon,
    createLabel: "Create Virtual Event",
    routes: {
      search: "/admin/events/virtuals/search",
      create: "/admin/events/virtuals/add/step-1",
      detail: "/admin/events/virtual/:eventId",
    },
    breadcrumbItems: [
      {
        label: 'Dashboard',
        to: '/admin/dashboard',
        icon: HomeIcon
      },
      {
        label: 'Events',
        to: '/admin/events',
        icon: CalendarDaysIcon
      },
      {
        label: 'Virtual Events',
        icon: ComputerDesktopIcon,
        isActive: true
      }
    ],
    columns,
    statusOptions,
    typeOptions: [], // No type filter needed for dedicated event type pages
    sortOptions,
    pageSizeOptions: PAGE_SIZE_OPTIONS.map(opt => ({
      value: opt.value,
      label: opt.label
    })),
    searchPlaceholder: "Search virtual events by name...",
    emptyState: {
      title: "No Virtual Events Found",
      filterDescription: "No virtual events match your current filters. Try adjusting your search criteria.",
      emptyDescription: "No virtual events have been added yet.",
      actionLabel: "Add Virtual Event"
    },
    fetchData,
    buildParams,
    renderGridItem,
    defaultStatus: String(EVENT_STATUS_ACTIVE),
    defaultType: "0",
    defaultSort: "startDate",
    defaultSortOrder: "DESC",
    defaultPageSize: 25,
    defaultViewType: "grid"
  };

  return <UniversalListPage config={config} />;
}

export default AdminEventVirtualListPage;