// File Path: monorepo/web/frontend/src/pages/Admin/EventOrder/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 { useEventOrderManager } from "../../../../../../services/Services";
import {
  UIXThemeProvider,
  EntityCommentsPage,
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
} from "../../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";

const AdminEventOrderDetailCommentListPageContent = memo(
  function AdminEventOrderDetailCommentListPageContent() {
    const { eventOrderID } = useParams();
    const eventOrderManager = useEventOrderManager();
    const { getThemeClasses } = useUIXTheme();

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

    const createComment = useCallback(
      async (entityId, content, onUnauthorized) => {
        return await eventOrderManager.createEventOrderComment(
          entityId,
          content,
          onUnauthorized,
        );
      },
      [],
    );  

    const buildFieldSections = useCallback(
      (eventOrder) => {
        if (!eventOrder || !eventOrder.id) return [];
        return [
          {
            type: "avatar",
            component: (
              <Avatar
                src={eventOrder.avatarObjectUrl}
                alt={
                  eventOrder.avatarObjectUrl
                    ? "Event Order"
                    : "No Event Order Image"
                }
                size="lg"
                borderStyle="default"
                showFallbackIcon={true}
              />
            ),
          },
          {
            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">
                    Event Order #{eventOrder.publicId || eventOrder.id}
                  </span>
                </h3>
                {eventOrder.eventName && (
                  <div
                    className={`mt-2 text-sm lg:text-base ${getThemeClasses("text.secondary")}`}
                  >
                    <Badge variant="primary" size="md">
                      {eventOrder.eventName}
                    </Badge>
                  </div>
                )}
              </div>
            ),
          },
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <AddressDisplay
                addressData={eventOrder}
                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={eventOrder.email}
                  size="md"
                  fallbackText="No email"
                />
                <ContactLink
                  type="phone"
                  value={eventOrder.phone}
                  size="md"
                  fallbackText="No phone"
                />
              </div>
            ),
          },
          {
            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">
                    {eventOrder.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>
                {eventOrder.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(eventOrder.createdAt)}
                    </span>
                  </div>
                )}
                {eventOrder.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(eventOrder.modifiedAt)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ].filter((section) => section.component);
      },
      [getThemeClasses],
    );

    const config = useMemo(
      () => ({
        entityId: eventOrderID,
        entityType: "event order",
        fetchEntity,
        createComment,
        breadcrumbs: {
          items: [
            { label: "Dashboard", to: "/admin/dashboard", icon: ChartBarIcon },
            {
              label: "Event Orders",
              to: "/admin/event-orders",
              icon: TicketIcon,
            },
            {
              label: "Comments",
              icon: ChatBubbleLeftRightIcon,
              isActive: true,
            },
          ],
        },
        header: {
          title: "Event Order - Comments",
          icon: ChatBubbleLeftRightIcon,
          loadingText: "Loading event order details...",
          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: () => {},
          },
        },
        actionButtons: (entity, entityId, navigate, isFetching) => [
          {
            variant: "outline",
            onClick: () => navigate("/admin/event-orders"),
            icon: ChevronLeftIcon,
            label: "Back",
          },
          {
            variant: "outline",
            icon: ArrowPathIcon,
            label: isFetching ? "Refreshing..." : "Refresh",
            disabled: isFetching,
          },
        ],
        tabs: {
          items: [
            {
              label: "Summary",
              to: `/admin/event-order/${eventOrderID}`,
              isActive: false,
            },
            {
              label: "Detail",
              to: `/admin/event-order/${eventOrderID}/detail`,
              isActive: false,
            },
            {
              label: "Comments",
              to: `/admin/event-order/${eventOrderID}/comments`,
              isActive: true,
            },
            {
              label: "Attachments",
              to: `/admin/event-order/${eventOrderID}/attachments`,
              isActive: false,
            },
            {
              label: "More",
              to: `/admin/event-order/${eventOrderID}/more`,
              icon: EllipsisHorizontalIcon,
              isActive: false,
            },
          ],
        },
        entityDisplay: {
          buildFieldSections,
          alerts: {
            archived: {
              message: "This event order is archived",
              icon: ArchiveBoxIcon,
            },
          },
          statusConfig: {
            activeLabel: "Active",
            inactiveLabel: "Archived",
            bannedLabel: "Archived",
          },
          typeMap: {},
        },
      }),
      [eventOrderID, fetchEntity, createComment, buildFieldSections],
    );

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

function AdminEventOrderDetailCommentListPage() {
  return (
    <UIXThemeProvider>
      <AdminEventOrderDetailCommentListPageContent />
    </UIXThemeProvider>
  );
}

export default AdminEventOrderDetailCommentListPage;
