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

import React, { useMemo, useCallback } from "react";
import {
  VideoCameraIcon,
  PaperClipIcon,
  EllipsisHorizontalIcon,
  ArchiveBoxIcon,
  CheckCircleIcon,
  HomeIcon,
  ChevronLeftIcon,
  LinkIcon,
  UserGroupIcon,
  ClockIcon,
} from "@heroicons/react/24/outline";
import {
  useAttachmentManager,
  useEventManager,
} from "../../../../../../../services/Services";
import {
  EntityAttachmentListPage,
  Badge,
  useUIXTheme,
} from "../../../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../../../services/Helpers/DateFormatter";
import { ATTACHMENT_OWNERSHIP_TYPE } from "../../../../../../../constants/Attachment";
import {
  EVENT_STATUS_ACTIVE,
  EVENT_STATUS_ARCHIVED,
} from "../../../../../../../constants/Event";

function AdminVirtualDetailAttachmentListPage() {
  const attachmentManager = useAttachmentManager();
  const eventManager = useEventManager();
  const { getThemeClasses } = useUIXTheme();

  // Memoized data fetching functions to prevent recreation on every render
  const fetchEntity = useCallback(async (eventId, onUnauthorized) => {
    return await eventManager.getEventDetail(eventId, onUnauthorized);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const fetchAttachments = useCallback(async (params, onUnauthorized) => {
    return await attachmentManager.getAttachments(params, onUnauthorized, true);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const onAttachmentClick = useCallback((attachment, eventId, navigate) => {
    navigate(`/admin/events/virtual/${eventId}/attachment/${attachment.id}`);
  }, []);

  const onDeleteAttachment = useCallback((attachment, eventId, navigate) => {
    navigate(
      `/admin/events/virtual/${eventId}/attachment/${attachment.id}/delete`,
    );
  }, []);

  // Memoized configuration object to prevent recreation on every render
  const config = useMemo(
    () => ({
      entityType: "virtual",
      entityIdParam: "eventId",
      defaultPageSize: 50,

      // Data fetching functions
      fetchEntity,
      fetchAttachments,

      // Attachment parameters
      attachmentParams: {
        ownershipRole: ATTACHMENT_OWNERSHIP_TYPE.EVENT,
      },

      // Header configuration
      header: {
        title: "Virtual Event - Attachments",
        icon: PaperClipIcon,
        loadingText: "Loading virtual event attachments...",
        notFoundTitle: "Virtual Event Not Found",
        notFoundMessage:
          "The virtual event you're looking for doesn't exist or you don't have permission to view it.",
        notFoundAction: {
          label: "Back to Virtual Events",
          icon: ChevronLeftIcon,
          onClick: () => (window.location.href = "/admin/events/virtuals"),
        },
      },

      // Route builders
      routes: {
        buildBreadcrumbs: (event, eventId) => [
          {
            label: "Dashboard",
            to: "/admin/dashboard",
            icon: HomeIcon,
          },
          {
            label: "Virtual Events",
            to: "/admin/events/virtuals",
            icon: VideoCameraIcon,
          },
          {
            label: event?.eventName || "Detail",
            to: `/admin/events/virtual/${eventId}`,
          },
          {
            label: "Attachments",
            icon: PaperClipIcon,
            isActive: true,
          },
        ],

        buildTabs: (event, eventId) => [
          {
            label: "Summary",
            to: `/admin/events/virtual/${eventId}`,
            isActive: false,
          },
          {
            label: "Details",
            to: `/admin/events/virtual/${eventId}/full`,
            isActive: false,
          },
          {
            label: "Event Orders",
            to: `/admin/events/virtual/${eventId}/event-orders`,
            isActive: false,
          },
          {
            label: "Event Contracts",
            to: `/admin/events/virtual/${eventId}/event-contracts`,
            isActive: false,
          },
          {
            label: "Comments",
            to: `/admin/events/virtual/${eventId}/comments`,
            isActive: false,
          },
          {
            label: "Attachments",
            to: `/admin/events/virtual/${eventId}/attachments`,
            isActive: true,
          },
          {
            label: "More",
            to: `/admin/events/virtual/${eventId}/more`,
            icon: EllipsisHorizontalIcon,
            isActive: false,
          },
        ],

        buildActionButtons: (event, eventId, navigate) => [
          {
            variant: "outline",
            onClick: () => navigate("/admin/events/virtuals"),
            icon: ChevronLeftIcon,
            label: "Back",
          },
          {
            variant: "outline",
            onClick: () => navigate(`/admin/events/virtual/${eventId}`),
            icon: ChevronLeftIcon,
            label: "Back to Detail",
          },
        ],

        addPath: `/admin/events/virtual/{entityId}/attachments/add`,
        viewPath: `/admin/events/virtual/{entityId}/attachment/{id}`,
        editPath: `/admin/events/virtual/{entityId}/attachment/{id}/edit`,
        deletePath: `/admin/events/virtual/{entityId}/attachment/{id}/delete`,
      },

      // Field sections builder
      buildFieldSections: (event) => {
        if (!event) return [];

        return [
          // Primary column sections
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <div>
                <h2
                  className={`text-lg sm:text-xl md:text-2xl lg:text-3xl font-bold ${getThemeClasses("text-primary")} flex items-center justify-center xl:justify-start mb-2`}
                >
                  <VideoCameraIcon className="w-6 h-6 mr-2 flex-shrink-0" />
                  <span className="break-words">
                    {event?.eventName || "Virtual Event"}
                  </span>
                </h2>
                <div
                  className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
                >
                  {event.status === EVENT_STATUS_ACTIVE ? (
                    <Badge variant="primary" size="sm">
                      <CheckCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Active
                    </Badge>
                  ) : (
                    <Badge variant="secondary" size="sm">
                      <ArchiveBoxIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Archived
                    </Badge>
                  )}
                </div>
              </div>
            ),
          },
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <div>
                {/* Event Details */}
                <div className="mb-3 text-center xl:text-left">
                  <h3
                    className={`text-base sm:text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}
                  >
                    Event Information
                  </h3>
                  {event?.startDateTime && (
                    <div
                      className={`text-sm sm:text-base ${getThemeClasses("text-secondary")} flex items-center justify-center xl:justify-start mb-1`}
                    >
                      <ClockIcon className="w-4 h-4 mr-2 flex-shrink-0" />
                      {formatDateForDisplay(event.startDateTime)}
                    </div>
                  )}
                  {event?.virtualMeetingUrl && (
                    <div
                      className={`text-sm sm:text-base ${getThemeClasses("text-secondary")} flex items-center justify-center xl:justify-start mb-1`}
                    >
                      <LinkIcon className="w-4 h-4 mr-2 flex-shrink-0" />
                      Virtual Meeting
                    </div>
                  )}
                  {event?.attendeeCapacity && (
                    <div
                      className={`text-sm sm:text-base ${getThemeClasses("text-secondary")} flex items-center justify-center xl:justify-start`}
                    >
                      <UserGroupIcon className="w-4 h-4 mr-2 flex-shrink-0" />
                      Capacity: {event.attendeeCapacity} attendees
                    </div>
                  )}
                </div>
              </div>
            ),
          },
          // Secondary column sections
          {
            column: "secondary",
            component: (
              <div
                className={`space-y-2 text-xs sm:text-sm lg:text-base ${getThemeClasses("text-secondary")}`}
              >
                {event?.createdAt && (
                  <div className="flex items-center justify-center xl:justify-start">
                    <CheckCircleIcon
                      className={`w-3 sm:w-4 h-3 sm:h-4 lg:w-5 lg:h-5 mr-2 ${getThemeClasses("text-muted")}`}
                    />
                    <span className="font-medium">Created:</span>
                    <span className="ml-2">
                      {formatDateForDisplay(event.createdAt)}
                    </span>
                  </div>
                )}
                {event?.modifiedAt && (
                  <div className="flex items-center justify-center xl:justify-start">
                    <CheckCircleIcon
                      className={`w-3 sm:w-4 h-3 sm:h-4 lg:w-5 lg:h-5 mr-2 ${getThemeClasses("text-muted")}`}
                    />
                    <span className="font-medium">Last Modified:</span>
                    <span className="ml-2">
                      {formatDateForDisplay(event.modifiedAt)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ].filter((section) => section.component);
      },

      // Alert builder
      buildAlerts: (event) => ({
        archived: {
          message: "This event is archived",
          icon: ArchiveBoxIcon,
        },
      }),

      // Permission check
      canAddAttachments: (event) => {
        return event ? event.status !== EVENT_STATUS_ARCHIVED : false;
      },

      // Event handlers
      onAttachmentClick,
      onDeleteAttachment,
    }),
    [fetchEntity, fetchAttachments, onAttachmentClick, onDeleteAttachment],
  );

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

export default AdminVirtualDetailAttachmentListPage;
