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

import React, { useMemo, memo } from "react";
import { useParams } from "react-router";
import {
  ChartBarIcon,
  BuildingOffice2Icon,
  ChatBubbleLeftRightIcon,
  ChevronLeftIcon,
  ArrowPathIcon,
  CalendarIcon,
  EllipsisHorizontalIcon,
  CheckCircleIcon,
  ArchiveBoxIcon,
  NoSymbolIcon,
} from "@heroicons/react/24/outline";
import { useOrganizationManager } from "../../../../../../services/Services";
import {
  UIXThemeProvider,
  EntityCommentsPage,
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
} from "../../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";
import {
  ORGANIZATION_STATUS_ACTIVE,
  ORGANIZATION_STATUS_ARCHIVED,
  ORGANIZATION_TYPE_MAP,
} from "../../../../../../constants/Organization";

const AdminOrganizationDetailCommentListPageContent = memo(function AdminOrganizationDetailCommentListPageContent() {
  const { id } = useParams();
  const organizationManager = useOrganizationManager();
  const { getThemeClasses } = useUIXTheme();

  const fetchEntity = useMemo(
    () => async (entityId, onUnauthorized) => {
      return await organizationManager.getOrganizationDetail(entityId, onUnauthorized);
    },
    [organizationManager]
  );

  const createComment = useMemo(
    () => async (entityId, content, onUnauthorized) => {
      return await organizationManager.createOrganizationComment(entityId, content, onUnauthorized);
    },
    [organizationManager]
  );

  // Helper function for getting primary contact - MEMOIZED
  const getPrimaryContact = useMemo(
    () => (organization) => {
      if (!organization?.contacts || organization.contacts.length === 0) return null;
      return organization.contacts.find((c) => c.isPrimary) || organization.contacts[0];
    },
    []
  );

  // Create status badge helper - MEMOIZED
  const createStatusBadge = useMemo(
    () => (organization) => {
      if (!organization) return null;
      if (organization.isBanned) {
        return <Badge variant="error" size="sm"><NoSymbolIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />Banned</Badge>;
      }
      if (organization.status === ORGANIZATION_STATUS_ACTIVE) {
        return <Badge variant="primary" size="sm"><CheckCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />Active</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 function - MEMOIZED
  const buildFieldSections = useMemo(
    () => (organization) => {
      if (!organization || !organization.id) return [];
      return [
        {
          type: "avatar",
          component: <Avatar src={organization.logoUrl} alt={organization.logoUrl ? "Organization Logo" : "No Logo"} size="lg" borderStyle="default" showFallbackIcon={true} fallbackIcon={BuildingOffice2Icon} />,
        },
        {
          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">{organization.organizationName || organization.name}</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>
          ),
        },
        {
          column: "primary",
          className: "mb-3 sm:mb-4 lg:mb-5",
          component: (
            <div>
              {getPrimaryContact(organization) && (
                <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(organization).firstName} {getPrimaryContact(organization).lastName}
                    {getPrimaryContact(organization).title && <span className={getThemeClasses("text-muted")}> - {getPrimaryContact(organization).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={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>
          ),
        },
        {
          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">
                  <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(organization.createdAt)}</span>
                </div>
              )}
              {organization.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(organization.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(organization)}</span>
              </div>
            </div>
          ),
        },
      ].filter((section) => section.component);
    },
    []
  );

  const config = useMemo(
    () => ({
      entityId: id,
      entityType: "organization",
      fetchEntity,
      createComment,
      breadcrumbs: {
        items: [
          { label: "Dashboard", to: "/admin/dashboard", icon: ChartBarIcon },
          { label: "Organizations", to: "/admin/organizations", icon: BuildingOffice2Icon },
          { label: "Comments", icon: ChatBubbleLeftRightIcon, isActive: true },
        ],
      },
      header: {
        title: "Organization - Comments",
        icon: ChatBubbleLeftRightIcon,
        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: () => {} },
      },
      actionButtons: (entity, entityId, navigate, isFetching) => [
        { variant: "outline", onClick: () => navigate("/admin/organizations"), icon: ChevronLeftIcon, label: "Back" },
        { variant: "outline", icon: ArrowPathIcon, label: isFetching ? "Refreshing..." : "Refresh", disabled: isFetching },
      ],
      tabs: {
        items: [
          { label: "Summary", to: `/admin/organization/${id}`, isActive: false },
          { label: "Details", to: `/admin/organization/${id}/full`, isActive: false },
          { 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: true },
          { label: "Attachments", to: `/admin/organization/${id}/attachments`, isActive: false },
          { label: "More", to: `/admin/organization/${id}/more`, icon: EllipsisHorizontalIcon, isActive: false },
        ],
      },
      entityDisplay: {
        buildFieldSections,
        alerts: {
          archived: { message: "This organization is archived", icon: ArchiveBoxIcon },
          banned: { message: "This organization is banned", icon: NoSymbolIcon },
        },
        statusConfig: { activeLabel: "Active", inactiveLabel: "Archived", bannedLabel: "Banned" },
        typeMap: ORGANIZATION_TYPE_MAP,
      },
    }),
    [id, fetchEntity, createComment, buildFieldSections]
  );

  return <EntityCommentsPage config={config} />;
});

function AdminOrganizationDetailCommentListPage() {
  return (
    <UIXThemeProvider>
      <AdminOrganizationDetailCommentListPageContent />
    </UIXThemeProvider>
  );
}

export default AdminOrganizationDetailCommentListPage;
