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

import React, { useMemo, useCallback } from "react";
import {
  TicketIcon,
  PaperClipIcon,
  EllipsisHorizontalIcon,
  ArchiveBoxIcon,
  CheckCircleIcon,
  XCircleIcon,
  HomeIcon,
  ChevronLeftIcon,
  CalendarDaysIcon,
  MapPinIcon,
  CurrencyDollarIcon,
} from "@heroicons/react/24/outline";
import {
  useAttachmentManager,
  useEventOrderManager,
} from "../../../../../../services/Services";
import {
  EntityAttachmentListPage,
  Badge,
  ContactLink,
  useUIXTheme,
} from "../../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";
import { ATTACHMENT_OWNERSHIP_TYPE } from "../../../../../../constants/Attachment";
import {
  EVENT_ORDER_STATUS_ACTIVE,
  EVENT_ORDER_STATUS_ARCHIVED,
} from "../../../../../../constants/EventOrder";

function AdminEventOrderDetailAttachmentListPage() {
  const attachmentManager = useAttachmentManager();
  const eventOrderManager = useEventOrderManager();
  const { getThemeClasses } = useUIXTheme();

  // Memoized data fetching functions to prevent recreation on every render
  // Note: We intentionally omit manager dependencies to prevent infinite loops
  // The managers are stable service instances from the Services container
  const fetchEntity = useCallback(async (eventOrderId, onUnauthorized) => {
    return await eventOrderManager.getEventOrderDetail(
      eventOrderId,
      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, eoid, navigate) => {
    navigate(`/admin/event-order/${eoid}/attachment/${attachment.id}`);
  }, []);

  const onDeleteAttachment = useCallback((attachment, eoid, navigate) => {
    navigate(`/admin/event-order/${eoid}/attachment/${attachment.id}/delete`);
  }, []);

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

      // Data fetching functions
      fetchEntity,
      fetchAttachments,

      // Attachment parameters
      attachmentParams: {
        ownershipId: "{entityId}",
        ownershipRole: ATTACHMENT_OWNERSHIP_TYPE.EVENT_ORDER,
      },

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

      // Route builders
      routes: {
        buildBreadcrumbs: (eventOrder, eoid) => [
          {
            label: "Dashboard",
            to: "/admin/dashboard",
            icon: HomeIcon,
          },
          {
            label: "Event Orders",
            to: "/admin/event-orders",
            icon: TicketIcon,
          },
          {
            label: `Order #${eventOrder.publicId || eoid}`,
            to: `/admin/event-order/${eoid}`,
          },
          {
            label: "Attachments",
            icon: PaperClipIcon,
            isActive: true,
          },
        ],

        buildTabs: (eventOrder, eoid) => [
          {
            label: "Quick View",
            to: `/admin/event-order/${eoid}`,
            isActive: false,
          },
          {
            label: "Full Details",
            to: `/admin/event-order/${eoid}/full`,
            isActive: false,
          },
          {
            label: "Comments",
            to: `/admin/event-order/${eoid}/comments`,
            isActive: false,
          },
          {
            label: "Attachments",
            to: `/admin/event-order/${eoid}/attachments`,
            isActive: true,
          },
          {
            label: "More Actions",
            to: `/admin/event-order/${eoid}/more`,
            icon: EllipsisHorizontalIcon,
            isActive: false,
          },
        ],

        buildActionButtons: (eventOrder, eoid, navigate) => [
          {
            variant: "outline",
            onClick: () => navigate("/admin/event-orders"),
            icon: ChevronLeftIcon,
            label: "Back",
          },
          {
            variant: "outline",
            onClick: () => navigate(`/admin/event-order/${eoid}`),
            icon: ChevronLeftIcon,
            label: "Back to Detail",
          },
        ],

        addPath: `/admin/event-order/{entityId}/attachments/add`,
        viewPath: `/admin/event-order/{entityId}/attachment/{id}`,
        editPath: `/admin/event-order/{entityId}/attachment/{id}/edit`,
        deletePath: `/admin/event-order/{entityId}/attachment/{id}/delete`,
      },

      // Field sections builder
      buildFieldSections: (eventOrder) => {
        if (!eventOrder) 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`}
                >
                  <TicketIcon className="w-6 h-6 mr-2 flex-shrink-0" />
                  <span className="break-words">
                    Event Order #{eventOrder?.publicId || "Unknown"}
                  </span>
                </h2>
                <div
                  className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
                >
                  {eventOrder.status === EVENT_ORDER_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 Order Details */}
                <div className="mb-3 text-center xl:text-left">
                  <h3
                    className={`text-base sm:text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}
                  >
                    Order Information
                  </h3>
                  {eventOrder?.eventName && (
                    <div
                      className={`text-sm sm:text-base ${getThemeClasses("text-secondary")} flex items-center justify-center xl:justify-start mb-1`}
                    >
                      <CalendarDaysIcon className="w-4 h-4 mr-2 flex-shrink-0" />
                      {eventOrder.eventName}
                    </div>
                  )}
                  {eventOrder?.grandTotal && (
                    <div
                      className={`text-sm sm:text-base ${getThemeClasses("text-secondary")} flex items-center justify-center xl:justify-start`}
                    >
                      <CurrencyDollarIcon className="w-4 h-4 mr-2 flex-shrink-0" />
                      Total: ${eventOrder.grandTotal}
                    </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")}`}
              >
                {eventOrder?.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(eventOrder.createdAt)}
                    </span>
                  </div>
                )}
                {eventOrder?.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(eventOrder.modifiedAt)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ].filter((section) => section.component);
      },

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

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

      // Event handlers
      onAttachmentClick,
      onDeleteAttachment,
    }),
    [fetchEntity, fetchAttachments, onAttachmentClick, onDeleteAttachment],
  );
  // Removed getThemeClasses from dependencies - it's used inside builders but doesn't need to trigger config recreation

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

export default AdminEventOrderDetailAttachmentListPage;
