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

import React, { useCallback } from "react";
import {
  BuildingOffice2Icon,
  ArchiveBoxIcon,
  ArchiveBoxXMarkIcon,
  NoSymbolIcon,
  TrashIcon,
  CheckCircleIcon,
  EllipsisHorizontalIcon,
  XCircleIcon,
} from "@heroicons/react/24/outline";
import { useDivisionManager } from "../../../../../services/Services";
import { EntityMorePage } from "../../../../../components/business/views";
import {
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
  UIXThemeProvider,
} from "../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../services/Helpers/DateFormatter";
import {
  DIVISION_STATUS_ACTIVE,
  DIVISION_STATUS_INACTIVE,
  DIVISION_STATUS_ARCHIVED,
  DIVISION_TYPE_LABELS,
} from "../../../../../constants/Division";

const DIVISION_CONSTANTS = {
  DIVISION_STATUS_ACTIVE,
  DIVISION_STATUS_ARCHIVED,
};

function AdminDivisionDetailMorePageContent() {
  const divisionManager = useDivisionManager();
  const { getThemeClasses } = useUIXTheme();

  // Memoized function to create tab items for division
  const createDivisionTabItems = useCallback(
    (division) => [
      {
        label: "Summary",
        href: `/admin/division/${division.id}`,
        isActive: false,
      },
      {
        label: "Details",
        href: `/admin/division/${division.id}/full`,
        isActive: false,
      },
      {
        label: "Events",
        href: `/admin/division/${division.id}/events`,
        isActive: false,
      },
      {
        label: "Orders",
        href: `/admin/division/${division.id}/orders`,
        isActive: false,
      },
      {
        label: "Comments",
        href: `/admin/division/${division.id}/comments`,
        isActive: false,
      },
      {
        label: "Attachments",
        href: `/admin/division/${division.id}/attachments`,
        isActive: false,
      },
      {
        label: "More",
        href: `/admin/division/${division.id}/more`,
        isActive: true,
        icon: EllipsisHorizontalIcon,
      },
    ],
    [],
  );

  // Memoized function to create action cards for division
  const createDivisionActionCards = useCallback(
    (division, divisionId, constants) => {
      const actionCards = [];

      if (division) {
        // Archive/Unarchive
        if (division.status === constants.DIVISION_STATUS_ARCHIVED) {
          actionCards.push({
            key: "unarchive",
            title: "Unarchive",
            subtitle: "Restore division to active status",
            icon: ArchiveBoxXMarkIcon,
            path: `/admin/division/${divisionId}/more/unarchive`,
            disabled: false,
          });
        } else {
          actionCards.push({
            key: "archive",
            title: "Archive",
            subtitle: "Remove division from active lists",
            icon: ArchiveBoxIcon,
            path: `/admin/division/${divisionId}/more/archive`,
            disabled: false,
          });
        }

        // Ban/Unban
        if (division.isBanned) {
          actionCards.push({
            key: "unban",
            title: "Remove Ban",
            subtitle: "Restore division access and operations",
            icon: CheckCircleIcon,
            path: `/admin/division/${divisionId}/more/unban`,
            disabled: false,
          });
        } else {
          actionCards.push({
            key: "ban",
            title: "Ban",
            subtitle: "Restrict division access and operations",
            icon: NoSymbolIcon,
            path: `/admin/division/${divisionId}/more/ban`,
            disabled: false,
          });
        }

        // Delete
        actionCards.push({
          key: "delete",
          title: "Delete",
          subtitle: "Permanently remove division and all data",
          icon: TrashIcon,
          path: `/admin/division/${divisionId}/more/delete`,
          disabled: false,
        });
      }

      return actionCards;
    },
    [],
  );

  // 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];
  }, []);

  // Build field sections for division summary card
  const buildFieldSections = useCallback(
    (division) => {
      if (!division) return [];

      const primaryContact = getPrimaryContact(division);

      return [
        // Primary column sections
        {
          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`}
              >
                <BuildingOffice2Icon 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: "space-y-2 sm:space-y-3",
          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>
          ),
        },
        // Secondary column sections
        {
          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);
    },
    [getPrimaryContact],
  ); // eslint-disable-line react-hooks/exhaustive-deps -- getThemeClasses intentionally excluded to prevent infinite loop

  // Custom get division detail function that uses the hook
  const getDivisionDetailWithManager = useCallback(
    async (divisionId, onUnauthorized) => {
      return new Promise((resolve, reject) => {
        divisionManager.getDivisionDetailWithCallbacks(
          divisionId,
          (divisionData) => resolve(divisionData), // onSuccess
          (error) => reject(error), // onError
          () => {}, // onDone
          onUnauthorized, // onUnauthorized
        );
      });
    },
    [divisionManager],
  );

  return (
    <EntityMorePage
      entityIcon={BuildingOffice2Icon}
      entityType="Division"
      entityTypePlural="Divisions"
      basePath="/admin/divisions"
      entityParamName="id"
      entityManager={divisionManager}
      getEntityDetail={getDivisionDetailWithManager}
      createTabItems={createDivisionTabItems}
      createActionCards={createDivisionActionCards}
      constants={DIVISION_CONSTANTS}
      infoMessage="Some actions may have different availability based on the division's status. Archived divisions have limited available actions."
      buildFieldSections={buildFieldSections}
    />
  );
}

function AdminDivisionDetailMorePage() {
  return (
    <UIXThemeProvider>
      <AdminDivisionDetailMorePageContent />
    </UIXThemeProvider>
  );
}

export default AdminDivisionDetailMorePage;
