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

import React, { useMemo, memo } from "react";
import { useParams } from "react-router";
import {
  ChartBarIcon,
  UserGroupIcon,
  ChatBubbleLeftRightIcon,
  ChevronLeftIcon,
  ArrowPathIcon,
  ClockIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  CheckCircleIcon,
  XCircleIcon,
  BuildingOfficeIcon,
  HomeIcon,
  StarIcon,
} from "@heroicons/react/24/outline";
import { StarIcon as StarIconSolid } from "@heroicons/react/24/solid";
import { useFacilitatorManager } from "../../../../../../services/Services";
import {
  UIXThemeProvider,
  EntityCommentsPage,
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
} from "../../../../../../components/UIX";
import {
  TagsDisplay,
  SkillSetsDisplay,
  CertificationDisplay,
} from "../../../../../../components/business/displays";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";
import { FACILITATOR_TYPE_OPTIONS } from "../../../../../../constants/Facilitator";

// Constants
const REPRESENTATIVE_FACILITATOR_TYPE_OF_ID = 2;
const INDIVIDUAL_FACILITATOR_TYPE_OF_ID = 1;

const AdminFacilitatorDetailCommentListPageContent = memo(
  function AdminFacilitatorDetailCommentListPageContent() {
    const { aid } = useParams();
    const facilitatorManager = useFacilitatorManager();

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

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

    // Helper function to get facilitator level label
    const getLevelLabel = useMemo(
      () => (level) => {
        switch (level) {
          case 1:
            return "Level 1 (in training)";
          case 2:
            return "Level 2 (secondary facilitator)";
          case 3:
            return "Level 3 (lead facilitator)";
          case 4:
            return "Level 4 (trainer)";
          default:
            return null;
        }
      },
      [],
    );

    // Helper function to format score rating
    const formatScoreRating = useMemo(
      () => (score) => {
        if (!score)
          return (
            <span className="opacity-60 text-sm sm:text-base lg:text-lg">
              No rating
            </span>
          );
        return (
          <div className="flex items-center gap-1">
            {[...Array(5)].map((_, i) => (
              <StarIconSolid
                key={i}
                className={`w-3 sm:w-4 h-3 sm:h-4 lg:w-5 lg:h-5 ${
                  i < Math.floor(score) ? "text-yellow-400" : "text-gray-300"
                }`}
              />
            ))}
            <span className="ml-2 text-sm sm:text-base lg:text-lg opacity-70 font-medium">
              ({score}/5)
            </span>
          </div>
        );
      },
      [],
    );

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

    const buildFieldSections = useMemo(
      () => (facilitator) => {
        if (!facilitator || !facilitator.id) return [];
        return [
          {
            type: "avatar",
            component: (
              <Avatar
                src={facilitator.avatarObjectUrl}
                alt={
                  facilitator.avatarObjectUrl
                    ? "Profile Picture"
                    : "No Profile Picture"
                }
                size="lg"
                borderStyle="default"
                showFallbackIcon={true}
              />
            ),
          },
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <div>
                {facilitator.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID &&
                  facilitator.representitiveOrganizationName && (
                    <h2 className="text-lg sm:text-xl md:text-2xl lg:text-3xl font-bold opacity-90 flex items-center justify-center xl:justify-start mb-2">
                      <BuildingOfficeIcon className="w-5 sm:w-6 h-5 sm:h-6 lg:w-8 lg:h-8 mr-2 lg:mr-3 flex-shrink-0 opacity-80" />
                      <span className="break-words">
                        {facilitator.representitiveOrganizationName}
                      </span>
                    </h2>
                  )}
                <h3 className="text-base sm:text-lg md:text-xl lg:text-2xl font-semibold opacity-90 flex items-center justify-center xl:justify-start">
                  {facilitator.type === INDIVIDUAL_FACILITATOR_TYPE_OF_ID && (
                    <HomeIcon className="w-4 sm:w-5 h-4 sm:h-5 lg:w-7 lg:h-7 mr-2 flex-shrink-0 opacity-80" />
                  )}
                  <span className="break-words">
                    {facilitator.name ||
                      `${facilitator.firstName} ${facilitator.lastName}`}
                  </span>
                </h3>
                <div className="mt-2 text-sm lg:text-base opacity-70 flex flex-wrap gap-2 justify-center xl:justify-start">
                  {facilitator.level && getLevelLabel(facilitator.level) && (
                    <Badge variant="info" size="md">
                      {getLevelLabel(facilitator.level)}
                    </Badge>
                  )}
                  {facilitator.isBanned ? (
                    <Badge variant="error" size="sm">
                      <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Banned
                    </Badge>
                  ) : facilitator.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>
                  )}
                </div>
              </div>
            ),
          },
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <div className="space-y-3">
                {facilitator.certifications &&
                  facilitator.certifications.length > 0 && (
                    <div className="flex flex-wrap gap-2 justify-center xl:justify-start">
                      <CertificationDisplay
                        values={extractIds(facilitator.certifications)}
                        onUnauthorized={() => {}}
                      />
                    </div>
                  )}
                {facilitator.skillSets && facilitator.skillSets.length > 0 && (
                  <div className="flex flex-wrap gap-2 justify-center xl:justify-start">
                    <SkillSetsDisplay
                      values={extractIds(facilitator.skillSets)}
                      onUnauthorized={() => {}}
                    />
                  </div>
                )}
              </div>
            ),
          },
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <AddressDisplay
                addressData={facilitator}
                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={facilitator.email}
                  size="md"
                  fallbackText="No email"
                />
                <ContactLink
                  type="phone"
                  value={facilitator.phone}
                  size="md"
                  fallbackText="No phone"
                />
                {facilitator.otherPhone && (
                  <ContactLink
                    type="phone"
                    value={facilitator.otherPhone}
                    size="md"
                    fallbackText="No phone"
                  />
                )}
              </div>
            ),
          },
          {
            column: "secondary",
            className: "mb-4 sm:mb-5",
            component: (
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium opacity-70">Type</label>
                  <p className="text-base opacity-90 mt-1">
                    {facilitator.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID
                      ? "Representative"
                      : facilitator.type === INDIVIDUAL_FACILITATOR_TYPE_OF_ID
                        ? "Individual"
                        : "Unassigned"}
                  </p>
                </div>

                <div>
                  <label className="text-sm font-medium opacity-70">
                    Rating
                  </label>
                  <div className="mt-1">
                    {formatScoreRating(facilitator.score)}
                  </div>
                </div>
              </div>
            ),
          },
          {
            column: "secondary",
            component: (
              <div className="space-y-2 text-xs sm:text-sm lg:text-base opacity-70">
                {facilitator.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 opacity-60" />
                    <span className="font-medium">Created:</span>
                    <span className="ml-2">
                      {formatDateForDisplay(facilitator.createdAt)}
                    </span>
                  </div>
                )}
                {facilitator.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 opacity-60" />
                    <span className="font-medium">Last Modified:</span>
                    <span className="ml-2">
                      {formatDateForDisplay(facilitator.modifiedAt)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ].filter((section) => section.component);
      },
      [],
    );

    const config = useMemo(
      () => ({
        entityId: aid,
        entityType: "facilitator",
        fetchEntity,
        createComment,
        breadcrumbs: {
          items: [
            { label: "Dashboard", to: "/admin/dashboard", icon: ChartBarIcon },
            {
              label: "Facilitators",
              to: "/admin/facilitators",
              icon: UserGroupIcon,
            },
            {
              label: "Comments",
              icon: ChatBubbleLeftRightIcon,
              isActive: true,
            },
          ],
        },
        header: {
          title: "Facilitator - Comments",
          icon: ChatBubbleLeftRightIcon,
          loadingText: "Loading facilitator details...",
          notFoundTitle: "Facilitator Not Found",
          notFoundMessage:
            "The facilitator you're looking for doesn't exist or you don't have permission to view it.",
          notFoundAction: {
            label: "Back to Facilitators",
            icon: ChevronLeftIcon,
            onClick: () => {},
          },
        },
        actionButtons: (entity, entityId, navigate, isFetching) => [
          {
            variant: "outline",
            onClick: () => navigate("/admin/facilitators"),
            icon: ChevronLeftIcon,
            label: "Back",
          },
          {
            variant: "outline",
            icon: ArrowPathIcon,
            label: isFetching ? "Refreshing..." : "Refresh",
            disabled: isFetching,
          },
        ],
        tabs: {
          items: [
            {
              label: "Summary",
              to: `/admin/facilitator/${aid}`,
              isActive: false,
            },
            {
              label: "Full Details",
              to: `/admin/facilitator/${aid}/detail`,
              isActive: false,
            },
            {
              label: "Event Contracts",
              to: `/admin/facilitator/${aid}/event-contracts`,
              isActive: false,
            },
            {
              label: "Comments",
              to: `/admin/facilitator/${aid}/comments`,
              isActive: true,
            },
            {
              label: "Attachments",
              to: `/admin/facilitator/${aid}/attachments`,
              isActive: false,
            },
            {
              label: "More",
              to: `/admin/facilitator/${aid}/more`,
              icon: EllipsisHorizontalIcon,
              isActive: false,
            },
          ],
        },
        entityDisplay: {
          buildFieldSections,
          alerts: {
            archived: {
              message: "This facilitator is archived",
              icon: ArchiveBoxIcon,
            },
            banned: {
              message: "This facilitator is banned",
              icon: XCircleIcon,
            },
          },
          statusConfig: {
            activeLabel: "Active",
            inactiveLabel: "Archived",
            bannedLabel: "Banned",
          },
          typeMap: FACILITATOR_TYPE_OPTIONS,
        },
      }),
      [aid, fetchEntity, createComment, buildFieldSections],
    );

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

function AdminFacilitatorDetailCommentListPage() {
  return (
    <UIXThemeProvider>
      <AdminFacilitatorDetailCommentListPageContent />
    </UIXThemeProvider>
  );
}

export default AdminFacilitatorDetailCommentListPage;
