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

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

function AdminEventContractDetailAttachmentListPage() {
  const attachmentManager = useAttachmentManager();
  const eventContractManager = useEventContractManager();
  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 (eventContractId, onUnauthorized) => {
    return await eventContractManager.getEventContractDetail(eventContractId, 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, eventContractId, navigate) => {
    navigate(`/admin/event-contract/${eventContractId}/attachment/${attachment.id}`);
  }, []);

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

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

    // Data fetching functions
    fetchEntity,
    fetchAttachments,

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

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

    // Route builders
    routes: {
      buildBreadcrumbs: (eventContract, eventContractId) => [
        {
          label: "Dashboard",
          to: "/admin/dashboard",
          icon: HomeIcon
        },
        {
          label: "Event Contracts",
          to: "/admin/event-contracts",
          icon: DocumentTextIcon
        },
        {
          label: `Contract #${eventContract.publicId || eventContractId}`,
          to: `/admin/event-contract/${eventContractId}`,
        },
        {
          label: "Attachments",
          icon: PaperClipIcon,
          isActive: true
        }
      ],

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

      buildActionButtons: (eventContract, eventContractId, navigate) => [
        {
          variant: "outline",
          onClick: () => navigate('/admin/event-contracts'),
          icon: ChevronLeftIcon,
          label: "Back"
        },
        {
          variant: "outline",
          onClick: () => navigate(`/admin/event-contract/${eventContractId}`),
          icon: ChevronLeftIcon,
          label: "Back to Detail"
        }
      ],

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

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

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

    // Permission check
    canAddAttachments: (eventContract) => {
      return eventContract ? eventContract.status !== 2 : 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 AdminEventContractDetailAttachmentListPage;
