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

import React, { useMemo, useCallback } from "react";
import {
  BriefcaseIcon,
  PaperClipIcon,
  EllipsisHorizontalIcon,
  ArchiveBoxIcon,
  CheckCircleIcon,
  XCircleIcon,
  HomeIcon,
  ChevronLeftIcon,
} from "@heroicons/react/24/outline";
import {
  useAttachmentManager,
  useStaffManager,
} 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 {
  STAFF_STATUS_ACTIVE,
  STAFF_STATUS_ARCHIVED,
  STAFF_TYPE_MAP,
} from "../../../../../../constants/Staff";

function AdminStaffDetailAttachmentListPage() {
  const attachmentManager = useAttachmentManager();
  const staffManager = useStaffManager();
  const { getThemeClasses } = useUIXTheme();

  const fetchEntity = useCallback(async (staffId, onUnauthorized) => {
    return await staffManager.getStaffDetail(staffId, 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, staffId, navigate) => {
    navigate(`/admin/staff/${staffId}/attachment/${attachment.id}`);
  }, []);

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

  const config = useMemo(
    () => ({
      entityType: "staff",
      entityIdParam: "aid",
      defaultPageSize: 50,

      fetchEntity,
      fetchAttachments,

      attachmentParams: {
        ownershipRole: ATTACHMENT_OWNERSHIP_TYPE.STAFF,
      },

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

      routes: {
        buildBreadcrumbs: (staff, staffId) => [
          { label: "Dashboard", to: "/admin/dashboard", icon: HomeIcon },
          { label: "Staff", to: "/admin/staff", icon: BriefcaseIcon },
          {
            label:
              staff?.name ||
              (staff?.firstName && staff?.lastName
                ? `${staff.firstName} ${staff.lastName}`
                : "Staff Detail"),
            to: `/admin/staff/${staffId}`,
          },
          { label: "Attachments", icon: PaperClipIcon, isActive: true },
        ],

        buildTabs: (staff, staffId) => [
          { label: "Summary", to: `/admin/staff/${staffId}`, isActive: false },
          {
            label: "Detail",
            to: `/admin/staff/${staffId}/detail`,
            isActive: false,
          },
          {
            label: "Comments",
            to: `/admin/staff/${staffId}/comments`,
            isActive: false,
          },
          {
            label: "Attachments",
            to: `/admin/staff/${staffId}/attachments`,
            isActive: true,
          },
          {
            label: "More",
            to: `/admin/staff/${staffId}/more`,
            icon: EllipsisHorizontalIcon,
            isActive: false,
          },
        ],

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

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

      buildFieldSections: (staff) => {
        if (!staff) 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`}
                >
                  <BriefcaseIcon className="w-6 h-6 mr-2 flex-shrink-0" />
                  <span className="break-words">
                    {staff?.name || `${staff?.firstName} ${staff?.lastName}`}
                  </span>
                </h2>
                <div
                  className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
                >
                  {staff.isBanned ? (
                    <Badge variant="error" size="sm">
                      <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Banned
                    </Badge>
                  ) : staff.status === STAFF_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>
                  )}
                </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={staff?.email}
                  size="md"
                  fallbackText="No email"
                />
                <ContactLink
                  type="phone"
                  value={staff?.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")}`}
              >
                {staff?.type && (
                  <div className="flex items-center justify-center xl:justify-start">
                    <span className="font-medium">Type:</span>
                    <span className="ml-2">
                      {STAFF_TYPE_MAP[staff.type] || "Unknown"}
                    </span>
                  </div>
                )}
                {staff?.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(staff.createdAt)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ].filter((section) => section.component);
      },

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

      canAddAttachments: (staff) => {
        return staff
          ? staff.status !== STAFF_STATUS_ARCHIVED && !staff.isBanned
          : false;
      },

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

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

export default AdminStaffDetailAttachmentListPage;
