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

import React, { useMemo, useCallback } from "react";
import {
  UserGroupIcon,
  PaperClipIcon,
  EllipsisHorizontalIcon,
  ArchiveBoxIcon,
  CheckCircleIcon,
  XCircleIcon,
  HomeIcon,
  ChevronLeftIcon,
  MapPinIcon,
  BuildingOffice2Icon,
} from "@heroicons/react/24/outline";
import {
  useAttachmentManager,
  useCustomerManager,
} 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 { CUSTOMER_STATUS } from "../../../../../../constants/Customer";
import { SETTINGS_PAGINATION } from "../../../../../../constants/Settings";

function AdminCustomerDetailAttachmentListPage() {
  const attachmentManager = useAttachmentManager();
  const customerManager = useCustomerManager();
  const { getThemeClasses } = useUIXTheme();

  const fetchEntity = useCallback(
    async (customerId, onUnauthorized) => {
      return await customerManager.getCustomerDetail(
        customerId,
        onUnauthorized,
      );
    },
    [customerManager],
  );

  const fetchAttachments = useCallback(
    async (params, onUnauthorized) => {
      return await attachmentManager.getAttachments(
        params,
        onUnauthorized,
        true,
      );
    },
    [attachmentManager],
  );

  const onAttachmentClick = useCallback((attachment, customerId, navigate) => {
    navigate(`/admin/customer/${customerId}/attachment/${attachment.id}`);
  }, []);

  const onDeleteAttachment = useCallback((attachment, customerId, navigate) => {
    navigate(
      `/admin/customer/${customerId}/attachment/${attachment.id}/delete`,
    );
  }, []);

  const config = useMemo(
    () => ({
      entityType: "customer",
      entityIdParam: "cid",
      defaultPageSize: SETTINGS_PAGINATION.DEFAULT_PAGE_SIZE,

      fetchEntity,
      fetchAttachments,

      attachmentParams: {
        ownershipRole: ATTACHMENT_OWNERSHIP_TYPE.CUSTOMER,
      },

      header: {
        title: "Customer - Attachments",
        icon: PaperClipIcon,
        loadingText: "Loading customer attachments...",
        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: () => (window.location.href = "/admin/customers"),
        },
      },

      routes: {
        buildBreadcrumbs: (customer, customerId) => [
          { label: "Dashboard", to: "/admin/dashboard", icon: HomeIcon },
          { label: "Customers", to: "/admin/customers", icon: UserGroupIcon },
          {
            label:
              customer?.name ||
              (customer?.firstName && customer?.lastName
                ? `${customer.firstName} ${customer.lastName}`
                : "Customer Detail"),
            to: `/admin/customer/${customerId}`,
          },
          { label: "Attachments", icon: PaperClipIcon, isActive: true },
        ],

        buildTabs: (customer, customerId) => [
          {
            label: "Summary",
            to: `/admin/customer/${customerId}`,
            isActive: false,
          },
          {
            label: "Detail",
            to: `/admin/customer/${customerId}/detail`,
            isActive: false,
          },
          {
            label: "Event Orders",
            to: `/admin/customer/${customerId}/event-orders`,
            isActive: false,
          },
          {
            label: "Comments",
            to: `/admin/customer/${customerId}/comments`,
            isActive: false,
          },
          {
            label: "Attachments",
            to: `/admin/customer/${customerId}/attachments`,
            isActive: true,
          },
          {
            label: "More",
            to: `/admin/customer/${customerId}/more`,
            icon: EllipsisHorizontalIcon,
            isActive: false,
          },
        ],

        buildActionButtons: (customer, customerId, navigate) => [
          {
            variant: "outline",
            onClick: () => navigate("/admin/customers"),
            icon: ChevronLeftIcon,
            label: "Back",
          },
          {
            variant: "outline",
            onClick: () => navigate(`/admin/customer/${customerId}`),
            icon: ChevronLeftIcon,
            label: "Back to Detail",
          },
        ],

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

      buildFieldSections: (customer) => {
        if (!customer) return [];

        return [
          {
            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`}
                >
                  <UserGroupIcon className="w-6 h-6 mr-2 flex-shrink-0" />
                  <span className="break-words">
                    {customer?.name ||
                      `${customer?.firstName} ${customer?.lastName}`}
                  </span>
                </h2>
                <div
                  className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
                >
                  {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>
                  ) : customer.status === CUSTOMER_STATUS.ARCHIVED ? (
                    <Badge variant="secondary" size="sm">
                      <ArchiveBoxIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Archived
                    </Badge>
                  ) : (
                    <Badge variant="secondary" size="sm">
                      <ArchiveBoxIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Inactive
                    </Badge>
                  )}
                </div>
              </div>
            ),
          },
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            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"
                />
              </div>
            ),
          },
          {
            column: "secondary",
            component: (
              <div
                className={`space-y-2 text-xs sm:text-sm lg:text-base ${getThemeClasses("text-secondary")}`}
              >
                {customer?.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(customer.createdAt)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ].filter((section) => section.component);
      },

      buildAlerts: () => ({
        archived: {
          message: "This customer is archived",
          icon: ArchiveBoxIcon,
        },
        banned: { message: "This customer is banned", icon: XCircleIcon },
      }),

      canAddAttachments: (customer) => {
        return customer
          ? customer.status !== CUSTOMER_STATUS.ARCHIVED && !customer.isBanned
          : false;
      },

      onAttachmentClick,
      onDeleteAttachment,
    }),
    [
      fetchEntity,
      fetchAttachments,
      onAttachmentClick,
      onDeleteAttachment,
      getThemeClasses,
    ],
  );

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

export default AdminCustomerDetailAttachmentListPage;
