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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import {
  CalendarDaysIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  HomeIcon,
  ClockIcon,
  UserGroupIcon,
  CalendarIcon,
  MapPinIcon,
} from "@heroicons/react/24/outline";
import {
  UniversalListPage,
  ViewButton,
  Badge,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  CertificationDisplay,
  SkillSetsDisplay,
} from "../../../../../components/business/displays";
import {
  useSkillSetManager,
  useCertificationManager,
} from "../../../../../services/Services";
import { PAGE_SIZE_OPTIONS } from "../../../../../constants/FieldOptions";
import {
  EVENT_TYPE_CONFERENCE,
  EVENT_STATUS_ACTIVE,
  EVENT_STATUS_ARCHIVED,
  EVENT_STATUS_CLOSED,
  EVENT_STATUS_MAP,
} from "../../../../../constants/Event";
import { useEventManager } from "../../../../../services/Services";
import {
  formatDateForDisplay,
  formatDate,
} from "../../../../../services/Helpers/DateFormatter";

function AdminEventConferenceListPage() {
  const eventManager = useEventManager();
  const skillSetManager = useSkillSetManager();
  const certificationManager = useCertificationManager();
  const { getThemeClasses } = useUIXTheme();

  // Extract IDs from array of objects for display components
  const extractIds = (items) => {
    if (!items || !Array.isArray(items)) return [];
    return items.map((item) => item.id || item.value).filter(Boolean);
  };

  // Handle unauthorized access for display components
  const onUnauthorized = () => {
    console.warn("Unauthorized access in conference list");
  };

  // Inline Skills Display Component
  const SkillsInline = ({ skillIds }) => {
    const [skills, setSkills] = React.useState([]);
    const [loading, setLoading] = React.useState(true);

    React.useEffect(() => {
      const fetchSkills = async () => {
        if (!skillIds || skillIds.length === 0) {
          setSkills([]);
          setLoading(false);
          return;
        }

        try {
          const options =
            await skillSetManager.getSkillSetSelectOptions(onUnauthorized);
          const mappedSkills = skillIds
            .map((skillId) => {
              const skillIdStr = String(skillId);
              const matchingOption = options.find((opt) => {
                const optionId = String(opt.value || opt.id);
                return optionId === skillIdStr;
              });

              return matchingOption
                ? {
                    id: skillId,
                    label:
                      matchingOption.label ||
                      matchingOption.text ||
                      matchingOption.name,
                  }
                : null;
            })
            .filter(Boolean);

          setSkills(mappedSkills);
        } catch (error) {
          console.error("Error fetching skill names:", error);
          setSkills([]);
        } finally {
          setLoading(false);
        }
      };

      fetchSkills();
    }, [skillIds]);

    if (loading) {
      return (
        <Badge variant="secondary" size="sm">
          Loading...
        </Badge>
      );
    }

    return (
      <>
        {skills.map((skill) => (
          <Badge key={skill.id} variant="primary" size="sm">
            {skill.label}
          </Badge>
        ))}
      </>
    );
  };

  // Inline Certifications Display Component
  const CertificationsInline = ({ certificationIds }) => {
    const [certifications, setCertifications] = React.useState([]);
    const [loading, setLoading] = React.useState(true);

    React.useEffect(() => {
      const fetchCertifications = async () => {
        if (!certificationIds || certificationIds.length === 0) {
          setCertifications([]);
          setLoading(false);
          return;
        }

        try {
          const options =
            await certificationManager.getCertificationSelectOptions(
              onUnauthorized,
            );
          const mappedCertifications = certificationIds
            .map((certId) => {
              const certIdStr = String(certId);
              const matchingOption = options.find((opt) => {
                const optionId = String(opt.value || opt.id);
                return optionId === certIdStr;
              });

              return matchingOption
                ? {
                    id: certId,
                    label:
                      matchingOption.label ||
                      matchingOption.text ||
                      matchingOption.name,
                  }
                : null;
            })
            .filter(Boolean);

          setCertifications(mappedCertifications);
        } catch (error) {
          console.error("Error fetching certification names:", error);
          setCertifications([]);
        } finally {
          setLoading(false);
        }
      };

      fetchCertifications();
    }, [certificationIds]);

    if (loading) {
      return (
        <Badge variant="secondary" size="sm">
          Loading...
        </Badge>
      );
    }

    return (
      <>
        {certifications.map((cert) => (
          <Badge key={cert.id} variant="primary" size="sm">
            {cert.label}
          </Badge>
        ))}
      </>
    );
  };

  // Format event date and time for display - MEMOIZED to prevent re-renders
  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 `${startDate} • ${startTime} - ${endTime}`;
    } catch (error) {
      return "—";
    }
  }, []);

  // 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_CONFERENCE); // Always filter for Conference 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 status filter - must check for empty string to allow "All Statuses"
    if (status !== "" && status !== null && status !== undefined) {
      const statusInt = parseInt(status, 10);
      filtersMap.set("status", statusInt);
    }

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

    return filtersMap;
  }, []); // Empty dependency array since EVENT_TYPE_CONFERENCE is a constant

  // 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`}
      >
        <div className="p-6">
          <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 || event.name || "Unnamed Event"}</span>
            </h3>

            {/* Certifications - now using new backend fields */}
            {event.certifications && event.certifications.length > 0 && (
              <div className="mt-2 ml-8 flex items-center gap-2">
                <span className="text-sm font-medium text-gray-700">
                  Certifications:
                </span>
                <div className="flex flex-wrap gap-1">
                  {event.certifications.map((cert) => (
                    <Badge key={cert.id} variant="primary" size="sm">
                      {cert.name}
                    </Badge>
                  ))}
                </div>
              </div>
            )}

            {/* Specializations - now using new backend fields */}
            {event.specializations && event.specializations.length > 0 && (
              <div className="mt-1 ml-8 flex items-center gap-2">
                <span className="text-sm font-medium text-gray-700">
                  Specializations:
                </span>
                <div className="flex flex-wrap gap-1">
                  {event.specializations.map((spec) => (
                    <Badge key={spec.id} variant="secondary" size="sm">
                      {spec.name}
                    </Badge>
                  ))}
                </div>
              </div>
            )}

            {/* Skillsets */}
            {event.skillSets && event.skillSets.length > 0 && (
              <div className="mt-1 ml-8 flex items-center gap-2">
                <span className="text-sm font-medium text-gray-700">
                  Skills:
                </span>
                <div className="flex flex-wrap gap-1">
                  <SkillsInline skillIds={extractIds(event.skillSets)} />
                </div>
              </div>
            )}
          </div>

          <div
            className={`space-y-2 text-base ${getThemeClasses("text-primary")} mb-4`}
          >
            {(event.startDateTime || event.endDateTime) && (
              <div className="flex items-center text-sm">
                <CalendarIcon
                  className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                />
                <span>
                  {formatEventDateTime(event.startDateTime, event.endDateTime)}
                </span>
              </div>
            )}
            {(event.locationWithFullAddress || event.location) && (
              <div className="flex items-center text-sm">
                <MapPinIcon
                  className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                />
                <span>{event.locationWithFullAddress || event.location}</span>
              </div>
            )}
            {(event.attendeeCapacity || event.maxAttendees) && (
              <div className="flex items-center text-sm">
                <UserGroupIcon
                  className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                />
                <span>
                  Max Attendees: {event.attendeeCapacity || event.maxAttendees}
                </span>
              </div>
            )}
          </div>

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

  // Column configuration for DataList - MEMOIZED to prevent recreating config
  const columns = useMemo(() => [
    {
      header: "Event Name",
      accessor: "name",
      type: "link",
      linkPath: "/admin/event/conference/:id",
      render: (value, event) => {
        if (!event) return "—";
        return (
          <div>
            <div className="flex items-center mb-1">
              <CalendarDaysIcon
                className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
              />
              <span className="font-medium">
                {event.eventName || event.name || "Unnamed Event"}
              </span>
            </div>

            {/* Certifications */}
            {event.certifications && event.certifications.length > 0 && (
              <div className="mb-1 flex items-center gap-2">
                <span className="text-sm font-medium text-gray-700">
                  Certifications:
                </span>
                <div className="flex flex-wrap gap-1">
                  {event.certifications.map((cert) => (
                    <Badge key={cert.id} variant="primary" size="sm">
                      {cert.name}
                    </Badge>
                  ))}
                </div>
              </div>
            )}

            {/* Specializations */}
            {event.specializations && event.specializations.length > 0 && (
              <div className="mb-1 flex items-center gap-2">
                <span className="text-sm font-medium text-gray-700">
                  Specializations:
                </span>
                <div className="flex flex-wrap gap-1">
                  {event.specializations.map((spec) => (
                    <Badge key={spec.id} variant="secondary" size="sm">
                      {spec.name}
                    </Badge>
                  ))}
                </div>
              </div>
            )}

            {/* Skillsets */}
            {event.skillSets && event.skillSets.length > 0 && (
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium text-gray-700">
                  Skills:
                </span>
                <div className="flex flex-wrap gap-1">
                  <SkillsInline skillIds={extractIds(event.skillSets)} />
                </div>
              </div>
            )}
          </div>
        );
      },
    },
    {
      header: "Date & Time",
      accessor: "startDateTime",
      render: (startDateTime, event) => {
        if (!event) return "—";
        if (!startDateTime && !event.endDateTime) return "—";
        return (
          <div className="space-y-1">
            <div className="flex items-center text-sm">
              <CalendarIcon className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`} />
              <span>
                {formatEventDateTime(event.startDateTime, event.endDateTime)}
              </span>
            </div>
          </div>
        );
      },
    },
    {
      header: "Location",
      accessor: "location",
      render: (location, event) => {
        if (!event) return "—";
        const locationText = event.locationWithFullAddress || event.location;
        if (!locationText) return "—";
        return (
          <div className="flex items-center text-sm">
            <MapPinIcon className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`} />
            <span className="truncate max-w-xs" title={locationText}>
              {locationText}
            </span>
          </div>
        );
      },
    },
    {
      header: "Attendees",
      accessor: "attendeeCapacity",
      render: (attendeeCapacity, event) => {
        if (!event) return "—";
        const capacity = event.attendeeCapacity || event.maxAttendees;
        if (!capacity) return "—";
        return (
          <div className="flex items-center text-sm">
            <UserGroupIcon className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`} />
            <span>Max: {capacity}</span>
          </div>
        );
      },
    },
    {
      header: "Actions",
      align: "right",
      render: (value, event) => {
        if (!event) return null;
        return (
          <ViewButton
            to={`/admin/events/conference/${event.id}`}
            text="View Event"
          />
        );
      },
    },
  ], []); // getThemeClasses removed - captured in closure

  // 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: "startDateTime,DESC",
      label: "Start Date & Time (Newest → Oldest)",
    },
    {
      value: "startDateTime,ASC",
      label: "Start Date & Time (Oldest → Newest)",
    },
    { value: "createdAt,DESC", label: "Created Date (Newest → Oldest)" },
    { value: "createdAt,ASC", label: "Created Date (Oldest → Newest)" },
  ];

  // UniversalListPage configuration - MEMOIZED to prevent infinite loops
  const config = useMemo(() => ({
    entityName: "Conference Event",
    entityNamePlural: "Conference Events",
    icon: CalendarDaysIcon,
    searchIcon: MagnifyingGlassIcon,
    createIcon: PlusIcon,
    createLabel: "Create Conference Event",
    routes: {
      search: "/admin/events/conferences/search",
      create: "/admin/events/conferences/add/step-1",
      detail: "/admin/events/conference/:id",
    },
    breadcrumbItems: [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: HomeIcon,
      },
      {
        label: "Events",
        to: "/admin/events",
        icon: CalendarDaysIcon,
      },
      {
        label: "Conference Events",
        icon: CalendarDaysIcon,
        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 conference events by name...",
    emptyState: {
      title: "No Conference Events Found",
      filterDescription:
        "No conference events match your current filters. Try adjusting your search criteria.",
      emptyDescription: "No conference events have been added yet.",
      actionLabel: "Add Conference Event",
    },
    fetchData,
    buildParams,
    renderGridItem,
    defaultStatus: String(EVENT_STATUS_ACTIVE), // "1" - Active by default
    defaultType: "",
    defaultSort: "startDateTime",
    defaultSortOrder: "DESC",
    defaultPageSize: 25,
    defaultViewType: "grid",
  }), [fetchData, buildParams, columns]);

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

export default AdminEventConferenceListPage;
