// File Path: monorepo/web/frontend/src/pages/Admin/Division/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 { useDivisionManager } from "../../../../../../services/Services";
import {
  UIXThemeProvider,
  EntityCommentsPage,
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
} 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";

const AdminDivisionDetailCommentListPageContent = memo(function AdminDivisionDetailCommentListPageContent() {
  const { id } = useParams();
  const divisionManager = useDivisionManager();
  const { getThemeClasses } = useUIXTheme();

  // Fetch entity function
  const fetchEntity = useMemo(
    () => async (entityId, onUnauthorized) => {
      return await divisionManager.getDivisionDetail(entityId, onUnauthorized);
    },
    [divisionManager]
  );

  // Create comment function
  const createComment = useMemo(
    () => async (entityId, content, onUnauthorized) => {
      return await divisionManager.createDivisionComment(
        entityId,
        content,
        onUnauthorized,
      );
    },
    [divisionManager]
  );

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

  // Create status badge helper - MEMOIZED
  const createStatusBadge = useMemo(
    () => (division) => {
      if (!division) return null;
      if (division.isBanned) {
        return (
          <Badge variant="error" size="sm">
            <NoSymbolIcon 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">
            <CheckCircleIcon 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 function
  const buildFieldSections = useMemo(
    () => (division) => {
      if (!division || !division.id) return [];

      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>
              {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>
              )}
              <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: (
            <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>
              {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);
    },
    []
  );

  // Entity comments page configuration
  const config = useMemo(
    () => ({
      entityId: id,
      entityType: "division",
      fetchEntity,
      createComment,

      breadcrumbs: {
        items: [
          {
            label: "Dashboard",
            to: "/admin/dashboard",
            icon: ChartBarIcon,
          },
          {
            label: "Divisions",
            to: "/admin/divisions",
            icon: BuildingOffice2Icon,
          },
          {
            label: "Comments",
            icon: ChatBubbleLeftRightIcon,
            isActive: true,
          },
        ],
      },

      header: {
        title: "Division - Comments",
        icon: ChatBubbleLeftRightIcon,
        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: () => {},
        },
      },

      actionButtons: (entity, entityId, navigate, isFetching) => [
        {
          variant: "outline",
          onClick: () => navigate("/admin/divisions"),
          icon: ChevronLeftIcon,
          label: "Back",
        },
        {
          variant: "outline",
          icon: ArrowPathIcon,
          label: isFetching ? "Refreshing..." : "Refresh",
          disabled: isFetching,
        },
      ],

      tabs: {
        items: [
          {
            label: "Summary",
            to: `/admin/division/${id}`,
            isActive: false,
          },
          {
            label: "Details",
            to: `/admin/division/${id}/full`,
            isActive: false,
          },
          {
            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: true,
          },
          {
            label: "Attachments",
            to: `/admin/division/${id}/attachments`,
            isActive: false,
          },
          {
            label: "More",
            to: `/admin/division/${id}/more`,
            icon: EllipsisHorizontalIcon,
            isActive: false,
          },
        ],
      },

      entityDisplay: {
        buildFieldSections,
        alerts: {
          archived: {
            message: "This division is archived",
            icon: ArchiveBoxIcon,
          },
          inactive: {
            message: "This division is inactive",
            icon: NoSymbolIcon,
          },
          banned: {
            message: "This division is banned",
            icon: NoSymbolIcon,
          },
        },
        statusConfig: {
          activeLabel: "Active",
          inactiveLabel: "Inactive",
          bannedLabel: "Banned",
        },
        typeMap: DIVISION_TYPE_LABELS,
      },
    }),
    [id, fetchEntity, createComment, buildFieldSections]
  );

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

// Main wrapper component
function AdminDivisionDetailCommentListPage() {
  return (
    <UIXThemeProvider>
      <AdminDivisionDetailCommentListPageContent />
    </UIXThemeProvider>
  );
}

export default AdminDivisionDetailCommentListPage;
