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

import React, { useState, useEffect, useCallback } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
  ChartBarIcon,
  BuildingOffice2Icon,
  InformationCircleIcon,
  ChevronLeftIcon,
  CheckCircleIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  NoSymbolIcon,
  BuildingOfficeIcon,
  CalendarDaysIcon,
  UserIcon,
  GlobeAltIcon,
  ServerIcon,
  CogIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";
import { useOrganizationManager, useAuthManager } from "../../../../services/Services";
import {
  TagsDisplay,
} from "../../../../components/business/displays";
import {
  DetailSection,
  DetailField,
} from "../../../../components/business/views";
import {
  DetailFullView,
  EditButton,
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  formatDateForDisplay,
  formatDateTime,
} from "../../../../services/Helpers/DateFormatter";
import {
  ORGANIZATION_STATUS_ACTIVE,
  ORGANIZATION_STATUS_ARCHIVED,
  ORGANIZATION_TYPE_MAP,
} from "../../../../constants/Organization";

const ORGANIZATION_SIZE_MAP = {
  1: "1-10 employees",
  2: "11-50 employees",
  3: "51-200 employees",
  4: "201-500 employees",
  5: "501-1000 employees",
  6: "1000+ employees",
};

const INDUSTRY_MAP = {
  1: "Technology",
  2: "Healthcare",
  3: "Finance",
  4: "Retail",
  5: "Manufacturing",
  6: "Education",
  7: "Other",
};

function AdminOrganizationDetailFullPageContent() {
  const { id } = useParams();
  const organizationManager = useOrganizationManager();
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

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

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

  // Fetch organization data
  const fetchOrganization = async () => {
    if (!id) return;

    setLoading(true);
    setError(null);

    organizationManager.getOrganizationDetailWithCallbacks(
      id,
      onFetchSuccess,
      onFetchError,
      onFetchDone,
      onUnauthorized,
    );
  };

  const onFetchSuccess = useCallback((response) => {
    // Organization detail fetched successfully
    setOrganization(response);
  }, []);

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

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

  // Initial data load
  useEffect(() => {
    window.scrollTo(0, 0);
    fetchOrganization();
  }, [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 = (organization) => {
    if (!organization) return "-";
    const parts = [];
    if (organization.addressLine1) parts.push(organization.addressLine1);
    if (organization.addressLine2) parts.push(organization.addressLine2);
    if (organization.city) parts.push(organization.city);
    if (organization.region) parts.push(organization.region);
    if (organization.postalCode) parts.push(organization.postalCode);
    if (organization.country) parts.push(organization.country);
    return parts.length > 0 ? parts.join(", ") : "-";
  };

  const getGoogleMapsUrl = (organization) => {
    if (!organization) return null;
    const address = formatAddress(organization);
    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 organization
  const getPrimaryContact = (organization) => {
    if (
      !organization ||
      !organization.contacts ||
      organization.contacts.length === 0
    ) {
      return null;
    }
    // Find primary contact or return first contact
    return (
      organization.contacts.find((c) => c.isPrimary) || organization.contacts[0]
    );
  };

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

  const headerConfig = {
    title: "Organization - Full Details",
    icon: BuildingOffice2Icon,
    loadingText: "Loading organization details...",
    notFoundTitle: "Organization Not Found",
    notFoundMessage: "The organization you're looking for doesn't exist or you don't have permission to view it.",
    notFoundAction: {
      label: "Back to Organizations",
      icon: ChevronLeftIcon,
      onClick: () => navigate('/admin/organizations')
    }
  };

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

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

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

  // Main InfoCard configuration
  const mainInfoCard = organization ? {
    title: "Organization Details",
    icon: BuildingOfficeIcon,
    avatar: (
      <Avatar
        src={organization.logoUrl}
        alt={organization.logoUrl ? "Organization Logo" : "No Logo"}
        size="lg"
        borderStyle="default"
        showFallbackIcon={true}
        fallbackIcon={BuildingOffice2Icon}
      />
    ),
    primarySections: [
      // Organization 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">
                {organization.organizationName || organization.name}
              </span>
            </h3>
            {organization.organizationShortName && (
              <p className={`text-sm sm:text-base ${getThemeClasses('text.secondary')} text-center xl:text-left mb-2`}>
                ({organization.organizationShortName})
              </p>
            )}
            <div className={`mt-2 text-base lg:text-lg ${getThemeClasses('text.secondary')}`}>
              <Badge variant="primary" size="md">
                {ORGANIZATION_TYPE_MAP[organization.organizationType] || "Unknown"}
              </Badge>
            </div>
          </div>
        )
      },
      // Address
      {
        className: 'mb-4 sm:mb-6',
        component: (
          <AddressDisplay
            addressData={organization}
            size="md"
            showIcon={true}
            showMapsLink={true}
          />
        )
      },
      // Contact Information
      {
        className: 'space-y-3',
        component: (
          <div className="space-y-3">
            <ContactLink
              type="email"
              value={getPrimaryContact(organization)?.email || organization?.contactEmail}
              size="md"
              fallbackText="No email"
            />
            <ContactLink
              type="phone"
              value={getPrimaryContact(organization)?.phone || organization?.contactPhone}
              size="md"
              fallbackText="No phone"
            />
            {organization?.website && (
              <ContactLink
                type="website"
                value={organization.website}
                size="md"
                fallbackText="No website"
              />
            )}
          </div>
        )
      }
    ],
    secondarySections: [
      // Tags
      {
        component: (
          <TagsDisplay
            values={organization?.tagIds || []}
            label="Tags"
            onUnauthorized={onUnauthorized}
          />
        )
      },
      // Additional Details
      {
        component: (
          <div className="space-y-4">
            {organization?.description && (
              <div>
                <h4 className={`text-lg font-bold ${getThemeClasses('text.primary')} flex items-center justify-center xl:justify-start mb-2`}>
                  Description
                </h4>
                <p className={`text-base ${getThemeClasses('text.secondary')} break-words`}>
                  {organization.description}
                </p>
              </div>
            )}
            {organization?.industry && (
              <div className="flex items-center justify-center xl:justify-start">
                <span className={`font-medium ${getThemeClasses('text.secondary')} w-20`}>Industry:</span>
                <span className={`ml-2 ${getThemeClasses('text.primary')}`}>
                  {INDUSTRY_MAP[organization.industry] || "Unknown"}
                </span>
              </div>
            )}
          </div>
        )
      }
    ]
  } : null;

  // Additional content sections
  const contentSections = organization ? [
    // Primary Contact Information (conditional)
    {
      type: 'conditional',
      condition: getPrimaryContact(organization),
      component: (
        <DetailSection title="Primary Contact Information" icon={UserIcon}>
          {getPrimaryContact(organization) && (
            <>
              <DetailField
                label="Contact Name"
                value={
                  `${getPrimaryContact(organization).firstName || ""} ${getPrimaryContact(organization).lastName || ""}`.trim() ||
                  "-"
                }
              />
              <DetailField
                label="Title"
                value={getPrimaryContact(organization).title}
              />
              <DetailField
                label="Email"
                value={
                  getPrimaryContact(organization).email ? (
                    <a
                      href={`mailto:${getPrimaryContact(organization).email}`}
                      className={`${getThemeClasses('link-primary')} break-all`}
                    >
                      {getPrimaryContact(organization).email}
                    </a>
                  ) : (
                    "-"
                  )
                }
              />
              <DetailField
                label="Phone"
                value={formatPhone(getPrimaryContact(organization).phone)}
              />
            </>
          )}
        </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">
              {organization.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')}`}>{organization.addressLine1}</span>
                </div>
              )}
              {organization.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')}`}>{organization.addressLine2}</span>
                </div>
              )}
              {organization.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')}`}>{organization.city}</span>
                </div>
              )}
            </div>
          )
        }
      ],
      secondarySections: [
        {
          className: 'space-y-4 text-base lg:text-lg',
          component: (
            <div className="space-y-4">
              {organization.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')}`}>{organization.region}</span>
                </div>
              )}
              {organization.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')}`}>{organization.postalCode}</span>
                </div>
              )}
              {organization.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')}`}>{organization.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">
                  {organization.isBanned ? (
                    <Badge variant="error" size="sm">
                      <NoSymbolIcon 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>
              {organization.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(organization.createdAt)}</span>
                </div>
              )}
              {organization.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')}`}>{organization.createdByUserName}</span>
                </div>
              )}
              {organization.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')}`}>{organization.createdFromIpAddress}</span>
                </div>
              )}
            </div>
          )
        }
      ],
      secondarySections: [
        {
          className: 'space-y-4 text-base lg:text-lg',
          component: (
            <div className="space-y-4">
              {organization.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(organization.modifiedAt)}</span>
                </div>
              )}
              {organization.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')}`}>{organization.modifiedByUserName}</span>
                </div>
              )}
              {organization.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')}`}>{organization.modifiedFromIpAddress}</span>
                </div>
              )}
            </div>
          )
        }
      ]
    }
  ].filter(section => section.condition !== false) : [];

  return (
    <DetailFullView
      entityData={organization}
      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 AdminOrganizationDetailFullPage() {
  return (
    <UIXThemeProvider>
      <AdminOrganizationDetailFullPageContent />
    </UIXThemeProvider>
  );
}

export default AdminOrganizationDetailFullPage;
