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

import React, { useMemo, useCallback } from "react";
import {
  BuildingOfficeIcon,
  PaperClipIcon,
  EllipsisHorizontalIcon,
  ArchiveBoxIcon,
  CheckCircleIcon,
  XCircleIcon,
  HomeIcon,
  ChevronLeftIcon,
} from "@heroicons/react/24/outline";
import {
  useAttachmentManager,
  useDivisionManager,
} from "../../../../../../services/Services";
import {
  EntityAttachmentListPage,
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
} from "../../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";
import { ATTACHMENT_OWNERSHIP_TYPE } from "../../../../../../constants/Attachment";
import {
  DIVISION_STATUS_ACTIVE,
  DIVISION_STATUS_INACTIVE,
  DIVISION_STATUS_ARCHIVED,
  DIVISION_TYPE_LABELS,
} from "../../../../../../constants/Division";

function AdminDivisionDetailAttachmentListPage() {
  const attachmentManager = useAttachmentManager();
  const divisionManager = useDivisionManager();
  const { getThemeClasses } = useUIXTheme();

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

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

  // Helper to get primary contact
  const getPrimaryContact = useCallback((division) => {
    if (!division?.contacts || division.contacts.length === 0) return null;
    return division.contacts.find((c) => c.isPrimary) || division.contacts[0];
  }, []);

  const config = useMemo(
    () => ({
      entityType: "division",
      entityIdParam: "id",
      defaultPageSize: 50,

      fetchEntity,
      fetchAttachments,

      attachmentParams: {
        ownershipRole: ATTACHMENT_OWNERSHIP_TYPE.DIVISION,
      },

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

      routes: {
        buildBreadcrumbs: (division, divisionId) => [
          { label: "Dashboard", to: "/admin/dashboard", icon: HomeIcon },
          {
            label: "Divisions",
            to: "/admin/divisions",
            icon: BuildingOfficeIcon,
          },
          {
            label:
              division?.divisionName || division?.name || "Division Detail",
            to: `/admin/division/${divisionId}`,
          },
          { label: "Attachments", icon: PaperClipIcon, isActive: true },
        ],

        buildTabs: (division, divisionId) => [
          {
            label: "Summary",
            to: `/admin/division/${divisionId}`,
            isActive: false,
          },
          {
            label: "Details",
            to: `/admin/division/${divisionId}/full`,
            isActive: false,
          },
          {
            label: "Events",
            to: `/admin/division/${divisionId}/events`,
            isActive: false,
          },
          {
            label: "Orders",
            to: `/admin/division/${divisionId}/orders`,
            isActive: false,
          },
          {
            label: "Comments",
            to: `/admin/division/${divisionId}/comments`,
            isActive: false,
          },
          {
            label: "Attachments",
            to: `/admin/division/${divisionId}/attachments`,
            isActive: true,
          },
          {
            label: "More",
            to: `/admin/division/${divisionId}/more`,
            icon: EllipsisHorizontalIcon,
            isActive: false,
          },
        ],

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

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

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

        const primaryContact = getPrimaryContact(division);

        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`}
                >
                  <BuildingOfficeIcon className="w-6 h-6 mr-2 flex-shrink-0" />
                  <span className="break-words">
                    {division?.divisionName ||
                      division?.name ||
                      "Unnamed Division"}
                  </span>
                </h2>
                {division?.divisionShortName && (
                  <p
                    className={`text-sm sm:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
                  >
                    ({division.divisionShortName})
                  </p>
                )}
                {division?.organizationName && (
                  <p
                    className={`text-sm sm:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left mt-1`}
                  >
                    Organization: {division.organizationName}
                  </p>
                )}
                <div
                  className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
                >
                  <Badge variant="primary" size="md">
                    {DIVISION_TYPE_LABELS[division?.divisionType] || "Unknown"}
                  </Badge>
                </div>
                <div
                  className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
                >
                  {division.isBanned ? (
                    <Badge variant="error" size="sm">
                      <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Banned
                    </Badge>
                  ) : division.status === DIVISION_STATUS_ACTIVE ? (
                    <Badge variant="primary" size="sm">
                      <CheckCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Active
                    </Badge>
                  ) : division.status === DIVISION_STATUS_INACTIVE ? (
                    <Badge variant="warning" size="sm">
                      <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Inactive
                    </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>
                {primaryContact && (
                  <div className="mb-3 text-center xl:text-left">
                    <h3
                      className={`text-base sm:text-lg font-semibold ${getThemeClasses("text-primary")} mb-2`}
                    >
                      Primary Contact
                    </h3>
                    <p
                      className={`text-sm sm:text-base ${getThemeClasses("text-secondary")}`}
                    >
                      {primaryContact.firstName} {primaryContact.lastName}
                      {primaryContact.title && (
                        <span className={getThemeClasses("text-muted")}>
                          {" "}
                          - {primaryContact.title}
                        </span>
                      )}
                    </p>
                  </div>
                )}
                <AddressDisplay
                  addressData={division}
                  size="md"
                  showIcon={true}
                  showMapsLink={true}
                />
              </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={primaryContact?.email || division?.contactEmail}
                  size="md"
                  fallbackText="No email"
                />
                <ContactLink
                  type="phone"
                  value={primaryContact?.phone || division?.contactPhone}
                  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")}`}
              >
                {division?.joinDate && (
                  <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">Join Date:</span>
                    <span className="ml-2">
                      {formatDateForDisplay(division.joinDate)}
                    </span>
                  </div>
                )}
                {division?.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(division.createdAt)}
                    </span>
                  </div>
                )}
                {division?.modifiedAt && (
                  <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">Last Modified:</span>
                    <span className="ml-2">
                      {formatDateForDisplay(division.modifiedAt)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ].filter((section) => section.component);
      },

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

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

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

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

export default AdminDivisionDetailAttachmentListPage;
