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

import React, { useMemo, memo } from "react";
import { useParams } from "react-router";
import {
  ChartBarIcon,
  ChatBubbleLeftRightIcon,
  ChevronLeftIcon,
  ArrowPathIcon,
  ClockIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  CheckCircleIcon,
  XCircleIcon,
  BriefcaseIcon,
} from "@heroicons/react/24/outline";
import { useStaffManager } from "../../../../../../services/Services";
import {
  UIXThemeProvider,
  EntityCommentsPage,
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
} from "../../../../../../components/UIX";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";
import { STAFF_TYPE_MAP } from "../../../../../../constants/Staff";

const AdminStaffDetailCommentListPageContent = memo(function AdminStaffDetailCommentListPageContent() {
  const { aid } = useParams();
  const staffManager = useStaffManager();
  const { getThemeClasses } = useUIXTheme();

  // Fetch entity function
  const fetchEntity = useMemo(
    () => async (entityId, onUnauthorized) => {
      return new Promise((resolve, reject) => {
        staffManager.getStaffDetailWithCallbacks(
          entityId,
          (response) => resolve(response),
          (errorResponse) => reject(errorResponse),
          () => {}, // onDone
          onUnauthorized,
        );
      });
    },
    [staffManager]
  );

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

  // Build field sections function
  const buildFieldSections = useMemo(
    () => (staff) => {
      if (!staff || !staff.id) return [];

      return [
        // Avatar section
        {
          type: "avatar",
          component: (
            <Avatar
              src={staff.avatarObjectUrl}
              alt={
                staff.avatarObjectUrl
                  ? "Profile Picture"
                  : "No Profile Picture"
              }
              size="lg"
              borderStyle="default"
              showFallbackIcon={true}
            />
          ),
        },
        // Primary column sections
        {
          column: "primary",
          className: "mb-3 sm:mb-4 lg:mb-5",
          component: (
            <div>
              {staff.type === 3 && staff.organizationName && (
                <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">
                    {staff.organizationName}
                  </span>
                </h2>
              )}
              <h3
                className={`text-base sm:text-lg md:text-xl lg:text-2xl font-semibold ${getThemeClasses("text.primary")} flex items-center justify-center xl:justify-start`}
              >
                <span className="break-words">
                  {staff.name || `${staff.firstName} ${staff.lastName}`}
                </span>
              </h3>
              <div
                className={`mt-2 text-sm lg:text-base ${getThemeClasses("text.secondary")}`}
              >
                <Badge variant="primary" size="md">
                  {STAFF_TYPE_MAP[staff.type] || "Unknown"}
                </Badge>
              </div>
            </div>
          ),
        },
        {
          column: "primary",
          className: "mb-3 sm:mb-4 lg:mb-5",
          component: (
            <AddressDisplay
              addressData={staff}
              size="md"
              showIcon={true}
              showMapsLink={true}
            />
          ),
        },
        {
          column: "primary",
          className: "space-y-2 sm:space-y-3",
          component: (
            <div className="space-y-2 sm:space-y-3">
              <ContactLink
                type="email"
                value={staff.email}
                size="md"
                fallbackText="No email"
              />
              <ContactLink
                type="phone"
                value={staff.phone}
                size="md"
                fallbackText="No phone"
              />
              {staff.otherPhone && (
                <ContactLink
                  type="phone"
                  value={staff.otherPhone}
                  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")}`}
            >
              <div className="flex items-center justify-center xl:justify-start">
                <ClockIcon
                  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">
                  {staff.isBanned ? (
                    <Badge variant="error" size="sm">
                      <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Banned
                    </Badge>
                  ) : staff.status === 1 ? (
                    <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>
                  )}
                </span>
              </div>
              {staff.createdAt && (
                <div className="flex items-center justify-center xl:justify-start">
                  <ClockIcon
                    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(staff.createdAt)}
                  </span>
                </div>
              )}
              {staff.modifiedAt && (
                <div className="flex items-center justify-center xl:justify-start">
                  <ClockIcon
                    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(staff.modifiedAt)}
                  </span>
                </div>
              )}
            </div>
          ),
        },
      ].filter((section) => section.component);
    },
    [getThemeClasses]
  );

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

      breadcrumbs: {
        items: [
          {
            label: "Dashboard",
            to: "/admin/dashboard",
            icon: ChartBarIcon,
          },
          {
            label: "Staff",
            to: "/admin/staff",
            icon: BriefcaseIcon,
          },
          {
            label: "Comments",
            icon: ChatBubbleLeftRightIcon,
            isActive: true,
          },
        ],
      },

      header: {
        title: "Staff Member - Comments",
        icon: ChatBubbleLeftRightIcon,
        loadingText: "Loading staff details...",
        notFoundTitle: "Staff Member Not Found",
        notFoundMessage:
          "The staff member you're looking for doesn't exist or you don't have permission to view it.",
        notFoundAction: {
          label: "Back to Staff",
          icon: ChevronLeftIcon,
          onClick: () => {},
        },
      },

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

      tabs: {
        items: [
          {
            label: "Summary",
            to: `/admin/staff/${aid}`,
            isActive: false,
          },
          {
            label: "Detail",
            to: `/admin/staff/${aid}/detail`,
            isActive: false,
          },
          {
            label: "Comments",
            to: `/admin/staff/${aid}/comments`,
            isActive: true,
          },
          {
            label: "Attachments",
            to: `/admin/staff/${aid}/attachments`,
            isActive: false,
          },
          {
            label: "More",
            to: `/admin/staff/${aid}/more`,
            icon: EllipsisHorizontalIcon,
            isActive: false,
          },
        ],
      },

      entityDisplay: {
        buildFieldSections,
        alerts: {
          archived: {
            message: "This staff member is archived",
            icon: ArchiveBoxIcon,
          },
          banned: {
            message: "This staff member is banned",
            icon: XCircleIcon,
          },
        },
        statusConfig: {
          activeLabel: "Active",
          inactiveLabel: "Archived",
          bannedLabel: "Banned",
        },
        typeMap: STAFF_TYPE_MAP,
      },
    }),
    [aid, fetchEntity, createComment, buildFieldSections]
  );

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

// Main wrapper component
function AdminStaffDetailCommentListPage() {
  return (
    <UIXThemeProvider>
      <AdminStaffDetailCommentListPageContent />
    </UIXThemeProvider>
  );
}

export default AdminStaffDetailCommentListPage;
