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

import React, { useMemo, memo } from "react";
import { useParams } from "react-router";
import {
  ChartBarIcon,
  UserIcon,
  ChatBubbleLeftRightIcon,
  ChevronLeftIcon,
  ArrowPathIcon,
  ClockIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  CheckCircleIcon,
  XCircleIcon,
} from "@heroicons/react/24/outline";
import { useCustomerManager } from "../../../../../../services/Services";
import {
  UIXThemeProvider,
  EntityCommentsPage,
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
} from "../../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";
import {
  CUSTOMER_ORGANIZATION_TYPE_LABELS,
  CUSTOMER_ORGANIZATION_TYPES,
  CUSTOMER_STATUS,
} from "../../../../../../constants/Customer";

const AdminCustomerDetailCommentListPageContent = memo(
  function AdminCustomerDetailCommentListPageContent() {
    const { cid } = useParams();
    const customerManager = useCustomerManager();
    const { getThemeClasses } = useUIXTheme();

    // Fetch entity function
    const fetchEntity = useMemo(
      () => async (entityId, onUnauthorized) => {
        return await customerManager.getCustomerDetail(
          entityId,
          onUnauthorized,
        );
      },
      [customerManager],
    );

    // Create comment function
    const createComment = useMemo(
      () => async (entityId, content, onUnauthorized) => {
        return await customerManager.createCustomerComment(
          entityId,
          content,
          onUnauthorized,
        );
      },
      [customerManager],
    );

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

        return [
          // Avatar section
          {
            type: "avatar",
            component: (
              <Avatar
                src={customer.avatarObjectUrl}
                alt={
                  customer.avatarObjectUrl
                    ? "Profile Picture"
                    : "No Profile Picture"
                }
                size="lg"
                borderStyle="default"
                showFallbackIcon={true}
              />
            ),
          },
          // Primary column sections
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <div>
                {customer.type === CUSTOMER_ORGANIZATION_TYPES.NON_PROFIT &&
                  customer.organizationName && (
                    <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`}
                    >
                      <span className="break-words">
                        {customer.organizationName}
                      </span>
                    </h2>
                  )}
                <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">
                    {customer.name ||
                      `${customer.firstName} ${customer.lastName}`}
                  </span>
                </h3>
                <div
                  className={`mt-2 text-sm lg:text-base ${getThemeClasses("text.secondary")}`}
                >
                  <Badge variant="primary" size="md">
                    {CUSTOMER_ORGANIZATION_TYPE_LABELS[customer.type] ||
                      "Unknown"}
                  </Badge>
                </div>
              </div>
            ),
          },
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <AddressDisplay
                addressData={customer}
                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={customer.email}
                  size="md"
                  fallbackText="No email"
                />
                <ContactLink
                  type="phone"
                  value={customer.phone}
                  size="md"
                  fallbackText="No phone"
                />
                {customer.otherPhone && (
                  <ContactLink
                    type="phone"
                    value={customer.otherPhone}
                    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">
                    {customer.isBanned ? (
                      <Badge variant="error" size="sm">
                        <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                        Banned
                      </Badge>
                    ) : customer.status === CUSTOMER_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>
                    )}
                  </span>
                </div>
                {customer.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(customer.createdAt)}
                    </span>
                  </div>
                )}
                {customer.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(customer.modifiedAt)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ].filter((section) => section.component);
      },
      [getThemeClasses],
    );

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

        breadcrumbs: {
          items: [
            {
              label: "Dashboard",
              to: "/admin/dashboard",
              icon: ChartBarIcon,
            },
            {
              label: "Customers",
              to: "/admin/customers",
              icon: UserIcon,
            },
            {
              label: "Comments",
              icon: ChatBubbleLeftRightIcon,
              isActive: true,
            },
          ],
        },

        header: {
          title: "Customer - Comments",
          icon: ChatBubbleLeftRightIcon,
          loadingText: "Loading customer details...",
          notFoundTitle: "Customer Not Found",
          notFoundMessage:
            "The customer you're looking for doesn't exist or you don't have permission to view it.",
          notFoundAction: {
            label: "Back to Customers",
            icon: ChevronLeftIcon,
            onClick: () => {},
          },
        },

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

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

        entityDisplay: {
          buildFieldSections,
          alerts: {
            archived: {
              message: "This customer is archived",
              icon: ArchiveBoxIcon,
            },
            banned: {
              message: "This customer is banned",
              icon: XCircleIcon,
            },
          },
          statusConfig: {
            activeLabel: "Active",
            inactiveLabel: "Archived",
            bannedLabel: "Banned",
          },
          typeMap: CUSTOMER_ORGANIZATION_TYPE_LABELS,
        },
      }),
      [cid, fetchEntity, createComment, buildFieldSections],
    );

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

// Main wrapper component
function AdminCustomerDetailCommentListPage() {
  return (
    <UIXThemeProvider>
      <AdminCustomerDetailCommentListPageContent />
    </UIXThemeProvider>
  );
}

export default AdminCustomerDetailCommentListPage;
