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

import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router";
import {
  ChartBarIcon,
  BuildingOffice2Icon,
  InformationCircleIcon,
  ChevronLeftIcon,
  CheckCircleIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  NoSymbolIcon,
  BuildingOfficeIcon,
  CalendarDaysIcon,
  UserIcon,
  GlobeAltIcon,
  ServerIcon,
  CogIcon,
  HomeIcon,
  PhoneIcon,
} from "@heroicons/react/24/outline";
import {
  useDivisionManager,
  useAuthManager,
} from "../../../../services/Services";
import { TagsDisplay } from "../../../../components/business/displays";
import {
  DetailSection,
  DetailField,
} from "../../../../components/business/views";
import {
  DetailFullView,
  EditButton,
  Badge,
  ContactLink,
  AddressDisplay,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  formatDateForDisplay,
  formatDateTime,
} from "../../../../services/Helpers/DateFormatter";
import {
  DIVISION_TYPE_LABELS,
  DIVISION_STATUS_ACTIVE,
  DIVISION_STATUS_INACTIVE,
  DIVISION_STATUS_ARCHIVED,
} from "../../../../constants/Division";

function AdminDivisionDetailFullPageContent() {
  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
  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };

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

    setLoading(true);
    setError(null);

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

  const onFetchSuccess = (response) => {
    // Division detail fetched successfully
    setDivision(response);
  };

  const onFetchError = (errorResponse) => {
    // console.error("Error fetching division detail:", errorResponse);
    setError(
      errorResponse.message ||
        "Failed to load division details. Please try again.",
    );
  };

  const onFetchDone = () => {
    setLoading(false);
  };

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

  // Utility functions
  const formatPhone = (phoneNumber) => {
    if (!phoneNumber) return "-";
    const cleaned = phoneNumber.replace(/\D/g, "");
    if (cleaned.length === 11 && cleaned.startsWith("1")) {
      return `+1 (${cleaned.slice(1, 4)}) ${cleaned.slice(
        4,
        7,
      )}-${cleaned.slice(7)}`;
    } else if (cleaned.length === 10) {
      return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(
        6,
      )}`;
    }
    return phoneNumber;
  };

  const formatAddress = (division) => {
    if (!division) return "-";
    const parts = [];
    if (division.addressLine1) parts.push(division.addressLine1);
    if (division.addressLine2) parts.push(division.addressLine2);
    if (division.city) parts.push(division.city);
    if (division.region) parts.push(division.region);
    if (division.postalCode) parts.push(division.postalCode);
    if (division.country) parts.push(division.country);
    return parts.length > 0 ? parts.join(", ") : "-";
  };

  const getGoogleMapsUrl = (division) => {
    if (!division) return null;
    const address = formatAddress(division);
    if (address === "-") return null;
    return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(address)}`;
  };

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

  // Get primary contact from division
  const getPrimaryContact = (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];
  };

  // Configure DetailFullView props
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: ChartBarIcon,
    },
    {
      label: "Divisions",
      to: "/admin/divisions",
      icon: BuildingOffice2Icon,
    },
    {
      label: "Detail",
      icon: InformationCircleIcon,
      isActive: true,
    },
  ];

  const headerConfig = {
    title: "Division - Full Details",
    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"),
    },
  };

  const actionButtons = [
    {
      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"
        />
      ),
    },
  ];

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

  const alerts = {
    archived: {
      message: "This division is archived",
      icon: ArchiveBoxIcon,
    },
    banned: {
      message: "This division is banned",
      icon: NoSymbolIcon,
    },
  };

  // Main InfoCard configuration
  const mainInfoCard = division
    ? {
        title: "Division Details",
        icon: BuildingOfficeIcon,
        primarySections: [
          // Division Name and Type
          {
            className: "mb-4 sm:mb-6",
            component: (
              <div>
                <h3
                  className={`text-xl sm:text-2xl md:text-3xl font-bold ${getThemeClasses("text.primary")} flex items-center justify-center xl:justify-start mb-2`}
                >
                  <BuildingOffice2Icon
                    className={`w-5 sm:w-6 md:w-7 h-5 sm:h-6 md:h-7 mr-2 ${getThemeClasses("text.secondary")} flex-shrink-0`}
                  />
                  <span className="break-words">
                    {division.divisionName || division.name}
                  </span>
                </h3>
                {division.divisionShortName && (
                  <p
                    className={`text-sm sm:text-base ${getThemeClasses("text.secondary")} text-center xl:text-left mb-2`}
                  >
                    ({division.divisionShortName})
                  </p>
                )}
                {division.organizationName && (
                  <p
                    className={`text-sm sm:text-base ${getThemeClasses("text.secondary")} text-center xl:text-left mb-2`}
                  >
                    Organization: {division.organizationName}
                  </p>
                )}
                <div
                  className={`mt-2 text-base lg:text-lg ${getThemeClasses("text.secondary")}`}
                >
                  <Badge variant="primary" size="md">
                    {DIVISION_TYPE_LABELS[division.divisionType] || "Unknown"}
                  </Badge>
                </div>
              </div>
            ),
          },
          // Address
          {
            className: "mb-4 sm:mb-6",
            component: (
              <AddressDisplay
                addressData={division}
                size="md"
                showIcon={true}
                showMapsLink={true}
              />
            ),
          },
          // Contact Information
          {
            className: "space-y-3",
            component: (
              <div className="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>
            ),
          },
        ],
        secondarySections: [
          // Tags
          {
            component: (
              <TagsDisplay
                values={division?.tagIds || []}
                label="Tags"
                onUnauthorized={onUnauthorized}
                variant="primary"
              />
            ),
          },
          // Additional Details
          {
            component: (
              <div className="space-y-4">
                {division?.additionalComment && (
                  <div>
                    <h4
                      className={`text-lg font-bold ${getThemeClasses("text.primary")} flex items-center justify-center xl:justify-start mb-2`}
                    >
                      Additional Information
                    </h4>
                    <p
                      className={`text-base ${getThemeClasses("text.secondary")} break-words`}
                    >
                      {division.additionalComment}
                    </p>
                  </div>
                )}
                {division?.joinDate && (
                  <div className="flex items-center justify-center xl:justify-start">
                    <span
                      className={`font-medium ${getThemeClasses("text.secondary")} w-24`}
                    >
                      Join Date:
                    </span>
                    <span className={`ml-2 ${getThemeClasses("text.primary")}`}>
                      {formatDateForDisplay(division.joinDate)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ],
      }
    : null;

  // Get phone type label
  const getPhoneTypeLabel = (phoneType) => {
    const typeMap = {
      0: "Unknown",
      1: "Mobile",
      2: "Work",
      3: "Home",
    };
    return typeMap[phoneType] || "Unknown";
  };

  // Additional content sections
  const contentSections = division
    ? [
        // All Contacts Information (conditional)
        {
          type: "conditional",
          condition: division.contacts && division.contacts.length > 0,
          component: (
            <DetailSection
              title={`Contact Information (${division.contacts?.length || 0} Contact${division.contacts?.length !== 1 ? "s" : ""})`}
              icon={UserIcon}
            >
              {division.contacts && division.contacts.length > 0 ? (
                <div className="space-y-6">
                  {division.contacts.map((contact, index) => (
                    <div
                      key={index}
                      className={`${index > 0 ? "pt-6 border-t border-gray-200 dark:border-gray-700" : ""}`}
                    >
                      {division.contacts.length > 1 && (
                        <h4
                          className={`text-lg font-semibold ${getThemeClasses("text.primary")} mb-4`}
                        >
                          Contact Person #{index + 1}
                        </h4>
                      )}

                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <DetailField
                          label="First Name"
                          value={contact.firstName || "-"}
                        />
                        <DetailField
                          label="Last Name"
                          value={contact.lastName || "-"}
                        />
                        <DetailField
                          label="Title"
                          value={contact.title || "-"}
                        />
                        <DetailField
                          label="Email"
                          value={
                            contact.email ? (
                              <a
                                href={`mailto:${contact.email}`}
                                className={`${getThemeClasses("link-primary")} break-all`}
                              >
                                {contact.email}
                              </a>
                            ) : (
                              "-"
                            )
                          }
                        />
                        <DetailField
                          label="OK to Email"
                          value={contact.isOkToEmail ? "Yes" : "No"}
                        />
                        <DetailField
                          label="Phone"
                          value={
                            contact.phone
                              ? `${formatPhone(contact.phone)} (${getPhoneTypeLabel(contact.phoneType)})`
                              : "-"
                          }
                        />
                        {contact.phoneType === 2 && contact.phoneExtension && (
                          <DetailField
                            label="Phone Extension"
                            value={contact.phoneExtension}
                          />
                        )}
                        {contact.otherPhone && (
                          <>
                            <DetailField
                              label="Other Phone"
                              value={`${formatPhone(contact.otherPhone)} (${getPhoneTypeLabel(contact.otherPhoneType)})`}
                            />
                            {contact.otherPhoneType === 2 &&
                              contact.otherPhoneExtension && (
                                <DetailField
                                  label="Other Phone Extension"
                                  value={contact.otherPhoneExtension}
                                />
                              )}
                          </>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className={`text-sm ${getThemeClasses("text.secondary")}`}>
                  No contacts available
                </p>
              )}
            </DetailSection>
          ),
        },
        // Address Information InfoCard
        {
          type: "infoCard",
          title: "Address Information",
          icon: BuildingOfficeIcon,
          showAvatar: false,
          twoColumn: true,
          primarySections: [
            {
              className: "space-y-4 text-base lg:text-lg",
              component: (
                <div className="space-y-4">
                  {division.addressLine1 && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-32`}
                      >
                        Street Address:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.addressLine1}
                      </span>
                    </div>
                  )}
                  {division.addressLine2 && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-32`}
                      >
                        Address Line 2:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.addressLine2}
                      </span>
                    </div>
                  )}
                  {division.city && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-32`}
                      >
                        City:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.city}
                      </span>
                    </div>
                  )}
                </div>
              ),
            },
          ],
          secondarySections: [
            {
              className: "space-y-4 text-base lg:text-lg",
              component: (
                <div className="space-y-4">
                  {division.region && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-32`}
                      >
                        State/Province:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.region}
                      </span>
                    </div>
                  )}
                  {division.postalCode && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-32`}
                      >
                        Postal Code:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.postalCode}
                      </span>
                    </div>
                  )}
                  {division.country && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-32`}
                      >
                        Country:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.country}
                      </span>
                    </div>
                  )}
                </div>
              ),
            },
          ],
        },
        // System Information InfoCard
        {
          type: "infoCard",
          title: "System Info",
          icon: ServerIcon,
          showAvatar: false,
          twoColumn: true,
          primarySections: [
            {
              className: "space-y-4 text-base lg:text-lg",
              component: (
                <div className="space-y-4">
                  <div className="flex items-center justify-center xl:justify-start">
                    <CogIcon
                      className={`w-5 h-5 mr-2 ${getThemeClasses("text.muted")}`}
                    />
                    <span
                      className={`font-medium ${getThemeClasses("text.secondary")} w-28`}
                    >
                      Status:
                    </span>
                    <div className="ml-3">
                      {division.isBanned ? (
                        <Badge variant="error" size="sm">
                          <NoSymbolIcon 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>
                      ) : (
                        <Badge variant="secondary" size="sm">
                          <ArchiveBoxIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                          Archived
                        </Badge>
                      )}
                    </div>
                  </div>
                  {division.createdAt && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <CalendarDaysIcon
                        className={`w-5 h-5 mr-2 ${getThemeClasses("text.muted")}`}
                      />
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-28`}
                      >
                        Created At:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {formatDateTime(division.createdAt)}
                      </span>
                    </div>
                  )}
                  {division.createdByUserName && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <UserIcon
                        className={`w-5 h-5 mr-2 ${getThemeClasses("text.muted")}`}
                      />
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-28`}
                      >
                        Created By:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.createdByUserName}
                      </span>
                    </div>
                  )}
                  {division.createdFromIPAddress && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <GlobeAltIcon
                        className={`w-5 h-5 mr-2 ${getThemeClasses("text.muted")}`}
                      />
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-28`}
                      >
                        Created From:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.createdFromIPAddress}
                      </span>
                    </div>
                  )}
                </div>
              ),
            },
          ],
          secondarySections: [
            {
              className: "space-y-4 text-base lg:text-lg",
              component: (
                <div className="space-y-4">
                  {division.modifiedAt && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <CalendarDaysIcon
                        className={`w-5 h-5 mr-2 ${getThemeClasses("text.muted")}`}
                      />
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-28`}
                      >
                        Modified At:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {formatDateTime(division.modifiedAt)}
                      </span>
                    </div>
                  )}
                  {division.modifiedByUserName && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <UserIcon
                        className={`w-5 h-5 mr-2 ${getThemeClasses("text.muted")}`}
                      />
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-28`}
                      >
                        Modified By:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.modifiedByUserName}
                      </span>
                    </div>
                  )}
                  {division.modifiedFromIPAddress && (
                    <div className="flex items-center justify-center xl:justify-start">
                      <GlobeAltIcon
                        className={`w-5 h-5 mr-2 ${getThemeClasses("text.muted")}`}
                      />
                      <span
                        className={`font-medium ${getThemeClasses("text.secondary")} w-28`}
                      >
                        Modified From:
                      </span>
                      <span
                        className={`ml-3 ${getThemeClasses("text.primary")}`}
                      >
                        {division.modifiedFromIPAddress}
                      </span>
                    </div>
                  )}
                </div>
              ),
            },
          ],
        },
      ].filter((section) => section.condition !== false)
    : [];

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

// Main component export
function AdminDivisionDetailFullPage() {
  return (
    <UIXThemeProvider>
      <AdminDivisionDetailFullPageContent />
    </UIXThemeProvider>
  );
}

export default AdminDivisionDetailFullPage;
