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

import React, { useMemo, memo, useCallback } from "react";
import { useParams } from "react-router";
import {
  ChartBarIcon,
  TicketIcon,
  ChatBubbleLeftRightIcon,
  ChevronLeftIcon,
  ArrowPathIcon,
  ClockIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  CheckCircleIcon,
} from "@heroicons/react/24/outline";
import { useEventContractManager } from "../../../../../../services/Services";
import {
  UIXThemeProvider,
  EntityCommentsPage,
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
} from "../../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";

const AdminEventContractDetailCommentListPageContent = memo(
  function AdminEventContractDetailCommentListPageContent() {
    const { eventContractID } = useParams();
    const eventContractManager = useEventContractManager();
    const { getThemeClasses } = useUIXTheme();

    // Fetch entity function
    const fetchEntity = useCallback(async (entityId, onUnauthorized) => {
      return await eventContractManager.getEventContractDetail(
        entityId,
        onUnauthorized,
      );
    }, []); // eslint-disable-line react-hooks/exhaustive-deps

    // Create comment function
    const createComment = useCallback(
      async (entityId, content, onUnauthorized) => {
        return await eventContractManager.createEventContractComment(
          entityId,
          content,
          onUnauthorized,
        );
      },
      [],
    ); // eslint-disable-line react-hooks/exhaustive-deps

    // Build field sections function
    const buildFieldSections = useCallback(
      (eventContract) => {
        if (!eventContract || !eventContract.id) return [];

        return [
          // Avatar section
          {
            type: "avatar",
            component: (
              <Avatar
                src={eventContract.avatarObjectUrl}
                alt={
                  eventContract.avatarObjectUrl
                    ? "Event Contract"
                    : "No Event Contract Image"
                }
                size="lg"
                borderStyle="default"
                showFallbackIcon={true}
              />
            ),
          },
          // Primary column sections
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <div>
                <h3
                  className={`text-base sm:text-lg md:text-xl lg:text-2xl font-semibold ${getThemeClasses("text.primary")} flex items-center justify-center xl:justify-start`}
                >
                  <span className="break-words">
                    Contract #{eventContract.publicId || eventContract.id}
                  </span>
                </h3>
                {eventContract.eventName && (
                  <div
                    className={`mt-2 text-sm lg:text-base ${getThemeClasses("text.secondary")}`}
                  >
                    <Badge variant="primary" size="md">
                      {eventContract.eventName}
                    </Badge>
                  </div>
                )}
              </div>
            ),
          },
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <AddressDisplay
                addressData={eventContract}
                size="md"
                showIcon={true}
                showMapsLink={true}
              />
            ),
          },
          {
            column: "primary",
            className: "space-y-2 sm:space-y-3",
            component: (
              <div className="space-y-2 sm:space-y-3">
                <ContactLink
                  type="email"
                  value={eventContract.email}
                  size="md"
                  fallbackText="No email"
                />
                <ContactLink
                  type="phone"
                  value={eventContract.phone}
                  size="md"
                  fallbackText="No phone"
                />
              </div>
            ),
          },
          // Secondary column sections
          {
            column: "secondary",
            component: (
              <div
                className={`space-y-2 text-xs sm:text-sm lg:text-base ${getThemeClasses("text.secondary")}`}
              >
                <div className="flex items-center justify-center xl:justify-start">
                  <ClockIcon
                    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">Status:</span>
                  <span className="ml-2">
                    {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>
                    )}
                  </span>
                </div>
                {eventContract.createdAt && (
                  <div className="flex items-center justify-center xl:justify-start">
                    <ClockIcon
                      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">
                    <ClockIcon
                      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);
      },
      [getThemeClasses],
    );

    // Entity comments page configuration
    const config = useMemo(
      () => ({
        entityId: eventContractID,
        entityType: "event contract",
        fetchEntity,
        createComment,

        breadcrumbs: {
          items: [
            {
              label: "Dashboard",
              to: "/admin/dashboard",
              icon: ChartBarIcon,
            },
            {
              label: "Event Contracts",
              to: "/admin/event-contracts",
              icon: TicketIcon,
            },
            {
              label: "Comments",
              icon: ChatBubbleLeftRightIcon,
              isActive: true,
            },
          ],
        },

        header: {
          title: "Event Contract - Comments",
          icon: ChatBubbleLeftRightIcon,
          loadingText: "Loading event contract details...",
          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: () => {},
          },
        },

        actionButtons: (entity, entityId, navigate, isFetching) => [
          {
            variant: "outline",
            onClick: () => navigate("/admin/event-contracts"),
            icon: ChevronLeftIcon,
            label: "Back",
          },
          {
            variant: "outline",
            icon: ArrowPathIcon,
            label: isFetching ? "Refreshing..." : "Refresh",
            disabled: isFetching,
          },
        ],

        tabs: {
          items: [
            {
              label: "Summary",
              to: `/admin/event-contract/${eventContractID}`,
              isActive: false,
            },
            {
              label: "Detail",
              to: `/admin/event-contract/${eventContractID}/detail`,
              isActive: false,
            },
            {
              label: "Comments",
              to: `/admin/event-contract/${eventContractID}/comments`,
              isActive: true,
            },
            {
              label: "Attachments",
              to: `/admin/event-contract/${eventContractID}/attachments`,
              isActive: false,
            },
            {
              label: "More",
              to: `/admin/event-contract/${eventContractID}/more`,
              icon: EllipsisHorizontalIcon,
              isActive: false,
            },
          ],
        },

        entityDisplay: {
          buildFieldSections,
          alerts: {
            archived: {
              message: "This event contract is archived",
              icon: ArchiveBoxIcon,
            },
          },
          statusConfig: {
            activeLabel: "Active",
            inactiveLabel: "Archived",
            bannedLabel: "Archived",
          },
          typeMap: {},
        },
      }),
      [eventContractID, fetchEntity, createComment, buildFieldSections],
    );

    return <EntityCommentsPage config={config} />;
  },
);

// Main wrapper component
function AdminEventContractDetailCommentListPage() {
  return (
    <UIXThemeProvider>
      <AdminEventContractDetailCommentListPageContent />
    </UIXThemeProvider>
  );
}

export default AdminEventContractDetailCommentListPage;
