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

import React, { useCallback, useMemo } from "react";
import {
  BuildingOffice2Icon,
  NoSymbolIcon,
  CheckCircleIcon,
  ArchiveBoxIcon,
  XCircleIcon,
  CalendarIcon,
} from "@heroicons/react/24/outline";
import {
  useDivisionManager,
} from "../../../../../../services/Services";
import { EntityActionConfirmationPage } from "../../../../../../components/business/views";
import {
  Badge,
  ContactLink,
  AddressDisplay,
  Avatar,
  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";

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

  // Get division detail function
  const getDivisionDetail = async (divisionId, onUnauthorized) => {
    return new Promise((resolve, reject) => {
      divisionManager.getDivisionDetailWithCallbacks(
        divisionId,
        (divisionData) => {
          // Check if division is already banned
          if (divisionData.isBanned) {
            reject(new Error("This division is already banned. Use the unban page to remove the ban."));
            return;
          }
          resolve(divisionData);
        },
        (error) => reject(error),
        () => {},
        onUnauthorized
      );
    });
  };

  // Execute ban action
  const onBanExecute = async (divisionId, onUnauthorized) => {
    return new Promise((resolve, reject) => {
      const banData = {
        division_id: divisionId,
      };

      divisionManager.banDivisionWithCallbacks(
        banData,
        (response) => resolve(response),
        (error) => reject(error),
        () => {},
        onUnauthorized
      );
    });
  };

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

  // Create status badge component (exact same as Organization Lite View)
  const createStatusBadge = useMemo(
    () => (division) => {
      if (!division) return null;
      if (division.isBanned) {
        return (
          <Badge variant="error" size="sm">
            <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
            Banned
          </Badge>
        );
      }
      if (division.status === DIVISION_STATUS_ACTIVE) {
        return (
          <Badge variant="primary" size="sm">
            <CheckCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
            Active
          </Badge>
        );
      }
      if (division.status === DIVISION_STATUS_INACTIVE) {
        return (
          <Badge variant="warning" size="sm">
            <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
            Inactive
          </Badge>
        );
      }
      return (
        <Badge variant="secondary" size="sm">
          <ArchiveBoxIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
          Archived
        </Badge>
      );
    },
    []
  );

  // Build field sections (exact same structure as Organization Lite View)
  const buildFieldSections = useCallback((division) => {
    if (!division) return [];

    const primaryContact = getPrimaryContact(division);

    return [
      // Avatar section
      {
        type: 'avatar',
        component: (
          <Avatar
            src={division?.logoUrl}
            alt={division?.logoUrl ? "Division Logo" : "No Logo"}
            size="lg"
            borderStyle="default"
            showFallbackIcon={true}
            fallbackIcon={BuildingOffice2Icon}
          />
        )
      },
      // 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`}>
              <span className="break-words">
                {division?.divisionName || division?.name}
              </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>
        )
      },
      {
        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">
                <CalendarIcon 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">
                <CalendarIcon 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">
                <CalendarIcon 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 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">Status:</span>
              <span className="ml-2">
                {createStatusBadge(division)}
              </span>
            </div>
          </div>
        )
      }
    ].filter(section => section.component);
  }, [getPrimaryContact, createStatusBadge]); // eslint-disable-line react-hooks/exhaustive-deps -- getThemeClasses intentionally excluded to prevent infinite loop

  return (
    <EntityActionConfirmationPage
      entityIcon={BuildingOffice2Icon}
      entityType="Division"
      entityTypePlural="Divisions"
      basePath="/admin/division"
      entityParamName="id"
      entityManager={divisionManager}
      getEntityDetail={getDivisionDetail}
      actionIcon={NoSymbolIcon}
      actionName="Ban"
      actionDescription="Ban this division and revoke all system access."
      actionWarningPoints={[
        "All division members will be immediately logged out",
        "They will not be able to log in again",
        "All access to the system will be revoked",
        "The division will not be able to place or manage any work orders",
        "The division will still appear in search results with a banned banner displayed",
        "This action should only be taken for serious violations or security concerns"
      ]}
      actionButtonText="Ban Division"
      actionButtonVariant="danger"
      onActionExecute={onBanExecute}
      successMessage="Division has been banned successfully!"
      redirectPath={null} // Stay on more page to see updated status
      buildFieldSections={buildFieldSections}
    />
  );
}

function AdminDivisionDetailMoreBanPage() {
  return (
    <UIXThemeProvider>
      <AdminDivisionDetailMoreBanPageContent />
    </UIXThemeProvider>
  );
}

export default AdminDivisionDetailMoreBanPage;
