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

import React, { useCallback } from "react";
import {
  BuildingOffice2Icon,
  ArchiveBoxIcon,
  ArchiveBoxXMarkIcon,
  NoSymbolIcon,
  TrashIcon,
  CheckCircleIcon,
  EllipsisHorizontalIcon,
  XCircleIcon,
} from "@heroicons/react/24/outline";
import { useOrganizationManager } 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 {
  ORGANIZATION_STATUS_ACTIVE,
  ORGANIZATION_STATUS_ARCHIVED,
  ORGANIZATION_TYPE_MAP,
} from "../../../../../constants/Organization";

const ORGANIZATION_CONSTANTS = {
  ORGANIZATION_STATUS_ACTIVE,
  ORGANIZATION_STATUS_ARCHIVED,
};

function AdminOrganizationDetailMorePageContent() {
  const organizationManager = useOrganizationManager();
  const { getThemeClasses } = useUIXTheme();

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

  // Memoized function to create action cards for organization
  const createOrganizationActionCards = useCallback(
    (organization, organizationId, constants) => {
      const actionCards = [];

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

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

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

      return actionCards;
    },
    [],
  );

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

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

      const primaryContact = getPrimaryContact(organization);

      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">
                  {organization?.organizationName ||
                    organization?.name ||
                    "Unnamed Organization"}
                </span>
              </h2>
              {organization?.organizationShortName && (
                <p
                  className={`text-sm sm:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
                >
                  ({organization.organizationShortName})
                </p>
              )}
              <div
                className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
              >
                <Badge variant="primary" size="md">
                  {ORGANIZATION_TYPE_MAP[organization?.organizationType] ||
                    "Unknown"}
                </Badge>
              </div>
              <div
                className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
              >
                {organization.isBanned ? (
                  <Badge variant="error" size="sm">
                    <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                    Banned
                  </Badge>
                ) : organization.status === ORGANIZATION_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>
              {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={organization}
                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 || organization?.contactEmail}
                size="md"
                fallbackText="No email"
              />
              <ContactLink
                type="phone"
                value={primaryContact?.phone || organization?.contactPhone}
                size="md"
                fallbackText="No phone"
              />
              {organization?.website && (
                <ContactLink
                  type="website"
                  value={organization.website}
                  size="md"
                  fallbackText="No website"
                />
              )}
            </div>
          ),
        },
        // Secondary column sections
        {
          column: "secondary",
          component: (
            <div
              className={`space-y-2 text-xs sm:text-sm lg:text-base ${getThemeClasses("text-secondary")}`}
            >
              {organization?.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(organization.createdAt)}
                  </span>
                </div>
              )}
              {organization?.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(organization.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 organization detail function that uses the hook
  const getOrganizationDetailWithManager = useCallback(
    async (organizationId, onUnauthorized) => {
      return new Promise((resolve, reject) => {
        organizationManager.getOrganizationDetailWithCallbacks(
          organizationId,
          (organizationData) => resolve(organizationData), // onSuccess
          (error) => reject(error), // onError
          () => {}, // onDone
          onUnauthorized, // onUnauthorized
        );
      });
    },
    [organizationManager],
  );

  return (
    <EntityMorePage
      entityIcon={BuildingOffice2Icon}
      entityType="Organization"
      entityTypePlural="Organizations"
      basePath="/admin/organizations"
      entityParamName="id"
      entityManager={organizationManager}
      getEntityDetail={getOrganizationDetailWithManager}
      createTabItems={createOrganizationTabItems}
      createActionCards={createOrganizationActionCards}
      constants={ORGANIZATION_CONSTANTS}
      infoMessage="Some actions may have different availability based on the organization's status. Archived organizations have limited available actions."
      buildFieldSections={buildFieldSections}
    />
  );
}

function AdminOrganizationDetailMorePage() {
  return (
    <UIXThemeProvider>
      <AdminOrganizationDetailMorePageContent />
    </UIXThemeProvider>
  );
}

export default AdminOrganizationDetailMorePage;
