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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useParams } from "react-router";
import {
  ChartBarIcon,
  BuildingOffice2Icon,
  InformationCircleIcon,
  ChevronLeftIcon,
  CheckCircleIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  NoSymbolIcon,
  XCircleIcon,
  HomeIcon,
  CalendarIcon,
} from "@heroicons/react/24/outline";
import {
  useDivisionManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  TagsDisplay,
} from "../../../../components/business/displays";
import {
  UIXThemeProvider,
  DetailLiteView,
  EditButton,
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
} from "../../../../components/UIX";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";
import {
  DIVISION_TYPE_LABELS,
  DIVISION_STATUS_ACTIVE,
  DIVISION_STATUS_INACTIVE,
  DIVISION_STATUS_ARCHIVED,
} from "../../../../constants/Division";

function AdminDivisionDetailLitePageContent() {
  const { id } = useParams();
  const divisionManager = useDivisionManager();
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // State management
  const [division, setDivision] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Handle unauthorized access - MEMOIZED
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Fetch callbacks - MEMOIZED
  const onFetchSuccess = useCallback((response) => {
    setDivision(response);
  }, []);

  const onFetchError = useCallback((errorResponse) => {
    setError(
      errorResponse.message ||
        "Failed to load division details. Please try again.",
    );
  }, []);

  const onFetchDone = useCallback(() => {
    setLoading(false);
  }, []);

  // Fetch division data - MEMOIZED
  const fetchDivision = useCallback(() => {
    if (!id) return;

    setLoading(true);
    setError(null);

    divisionManager.getDivisionDetailWithCallbacks(
      id,
      onFetchSuccess,
      onFetchError,
      onFetchDone,
      onUnauthorized,
    );
  }, [id, divisionManager, onFetchSuccess, onFetchError, onFetchDone, onUnauthorized]);

  // Initial data load
  useEffect(() => {
    window.scrollTo(0, 0);
    fetchDivision();
  }, [fetchDivision]);

  // Extract IDs from array of objects - MEMOIZED
  const extractIds = useMemo(
    () => (items) => {
      if (!items || !Array.isArray(items)) return [];
      return items.map((item) => item.id || item.value).filter(Boolean);
    },
    []
  );

  // Get primary contact from division - MEMOIZED
  const getPrimaryContact = useMemo(
    () => (division) => {
      if (
        !division ||
        !division.contacts ||
        division.contacts.length === 0
      ) {
        return null;
      }
      // Find primary contact or return first contact
      return (
        division.contacts.find((c) => c.isPrimary) || division.contacts[0]
      );
    },
    []
  );

  // Create status badge component (theme-aware, will be rendered inside DetailLiteView) - MEMOIZED
  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">
        Archived
      </Badge>
    );
    },
    []
  );

  // Configure DetailLiteView props - ALL MEMOIZED
  const breadcrumbItems = useMemo(() => [
    {
      label: 'Dashboard',
      to: '/admin/dashboard',
      icon: HomeIcon,
      hideOnMobile: false,
      mobileLabel: 'Dash'
    },
    {
      label: 'Divisions',
      to: '/admin/divisions',
      icon: BuildingOffice2Icon
    },
    {
      label: 'Detail',
      icon: InformationCircleIcon,
      isActive: true
    }
  ], []);

  const headerConfig = useMemo(() => ({
    title: "Division - Summary",
    icon: BuildingOffice2Icon,
    loadingText: "Loading division details...",
    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: () => navigate('/admin/divisions')
    }
  }), [navigate]);

  const actionButtons = useMemo(() => [
    {
      variant: "outline",
      onClick: () => navigate('/admin/divisions'),
      icon: ChevronLeftIcon,
      label: "Back"
    },
    {
      component: (
        <EditButton
          onClick={() => navigate(`/admin/division/${id}/edit`)}
          disabled={division?.status === DIVISION_STATUS_ARCHIVED}
          variant="primary"
          className="flex-1 sm:flex-initial"
        />
      )
    }
  ], [id, division?.status, navigate]);

  const tabs = useMemo(() => [
    {
      label: "Summary",
      isActive: true
    },
    {
      label: "Details",
      to: `/admin/division/${division?.id}/full`
    },
    {
      label: "Events",
      to: `/admin/division/${division?.id}/events`
    },
    {
      label: "Orders",
      to: `/admin/division/${division?.id}/orders`
    },
    {
      label: "Comments",
      to: `/admin/division/${division?.id}/comments`
    },
    {
      label: "Attachments",
      to: `/admin/division/${division?.id}/attachments`
    },
    {
      label: "More",
      to: `/admin/division/${division?.id}/more`,
      icon: EllipsisHorizontalIcon
    }
  ], [division?.id]);

  const fieldSections = useMemo(() => [
    // 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>
          {/* Primary Contact */}
          {getPrimaryContact(division) && (
            <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")}`}>
                {getPrimaryContact(division).firstName}{" "}
                {getPrimaryContact(division).lastName}
                {getPrimaryContact(division).title && (
                  <span className={getThemeClasses("text-muted")}>
                    {" "}
                    - {getPrimaryContact(division).title}
                  </span>
                )}
              </p>
            </div>
          )}
          {/* Address */}
          <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={getPrimaryContact(division)?.email || division?.contactEmail}
            size="md"
            fallbackText="No email"
          />
          <ContactLink
            type="phone"
            value={getPrimaryContact(division)?.phone || division?.contactPhone}
            size="md"
            fallbackText="No phone"
          />
        </div>
      )
    },
    // Secondary column sections
    {
      column: 'secondary',
      component: (
        <TagsDisplay
          values={extractIds(division?.tags)}
          label="Tags"
          onUnauthorized={onUnauthorized}
        />
      )
    },
    {
      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>
          {/* Additional Comment */}
          {division?.additionalComment && (
            <div className={`mt-4 pt-4 border-t ${getThemeClasses("border-secondary")}`}>
              <h4 className={`text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}>
                Additional Information
              </h4>
              <p className={`text-xs sm:text-sm ${getThemeClasses("text-secondary")} leading-relaxed`}>
                {division.additionalComment}
              </p>
            </div>
          )}
        </div>
      )
    }
  ].filter(section => section.component), [division, getPrimaryContact, extractIds, onUnauthorized, createStatusBadge, getThemeClasses]); // Filter out sections with falsy components

  const alerts = useMemo(() => ({
    archived: {
      message: "This division is archived",
      icon: ArchiveBoxIcon
    },
    banned: {
      message: "This division is banned",
      icon: NoSymbolIcon
    }
  }), []);

  return (
    <DetailLiteView
      entityData={division}
      breadcrumbItems={breadcrumbItems}
      headerConfig={headerConfig}
      fieldSections={fieldSections}
      actionButtons={actionButtons}
      tabs={tabs}
      alerts={alerts}
      onUnauthorized={onUnauthorized}
      isLoading={loading}
      error={error}
      onErrorClose={() => setError(null)}
    />
  );
}

function AdminDivisionDetailLitePage() {
  return (
    <UIXThemeProvider>
      <AdminDivisionDetailLitePageContent />
    </UIXThemeProvider>
  );
}

export default AdminDivisionDetailLitePage;
