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

import React, { useMemo, useCallback } from "react";
import {
  UserGroupIcon,
  PaperClipIcon,
  EllipsisHorizontalIcon,
  ArchiveBoxIcon,
  CheckCircleIcon,
  XCircleIcon,
  HomeIcon,
  ChevronLeftIcon,
  ClockIcon,
  BuildingOfficeIcon,
} from "@heroicons/react/24/outline";
import { StarIcon as StarIconSolid } from "@heroicons/react/24/solid";
import {
  useAttachmentManager,
  useFacilitatorManager,
} from "../../../../../../services/Services";
import {
  EntityAttachmentListPage,
  Badge,
  ContactLink,
  AddressDisplay,
  Avatar,
} from "../../../../../../components/UIX";
import {
  TagsDisplay,
  SkillSetsDisplay,
  CertificationDisplay,
} from "../../../../../../components/business/displays";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";
import { ATTACHMENT_OWNERSHIP_TYPE } from "../../../../../../constants/Attachment";
import {
  FACILITATOR_STATUS_ACTIVE,
  FACILITATOR_STATUS_ARCHIVED,
} from "../../../../../../constants/Facilitator";

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

function AdminFacilitatorDetailAttachmentListPage() {
  const attachmentManager = useAttachmentManager();
  const facilitatorManager = useFacilitatorManager();

  // Helper function to get facilitator level label
  const getLevelLabel = useCallback((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 = useCallback((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 = useCallback((items) => {
    if (!items || !Array.isArray(items)) return [];
    return items.map((item) => item.id || item.value).filter(Boolean);
  }, []);

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

  const fetchAttachments = useCallback(async (params, onUnauthorized) => {
    return await attachmentManager.getAttachments(params, onUnauthorized, true);
  }, [attachmentManager]);

  const onAttachmentClick = useCallback(
    (attachment, facilitatorId, navigate) => {
      navigate(
        `/admin/facilitator/${facilitatorId}/attachment/${attachment.id}`,
      );
    },
    [],
  );

  const onDeleteAttachment = useCallback(
    (attachment, facilitatorId, navigate) => {
      navigate(
        `/admin/facilitator/${facilitatorId}/attachment/${attachment.id}/delete`,
      );
    },
    [],
  );

  const config = useMemo(
    () => ({
      entityType: "facilitator",
      entityIdParam: "aid",
      defaultPageSize: 50,

      fetchEntity,
      fetchAttachments,

      attachmentParams: {
        ownershipRole: ATTACHMENT_OWNERSHIP_TYPE.FACILITATOR,
      },

      header: {
        title: "Facilitator - Attachments",
        icon: PaperClipIcon,
        loadingText: "Loading facilitator attachments...",
        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: () => (window.location.href = "/admin/facilitators"),
        },
      },

      routes: {
        buildBreadcrumbs: (facilitator, facilitatorId) => [
          { label: "Dashboard", to: "/admin/dashboard", icon: HomeIcon },
          {
            label: "Facilitators",
            to: "/admin/facilitators",
            icon: UserGroupIcon,
          },
          {
            label:
              facilitator?.name ||
              (facilitator?.firstName && facilitator?.lastName
                ? `${facilitator.firstName} ${facilitator.lastName}`
                : "Facilitator Detail"),
            to: `/admin/facilitator/${facilitatorId}`,
          },
          { label: "Attachments", icon: PaperClipIcon, isActive: true },
        ],

        buildTabs: (facilitator, facilitatorId) => [
          {
            label: "Summary",
            to: `/admin/facilitator/${facilitatorId}`,
            isActive: false,
          },
          {
            label: "Full Details",
            to: `/admin/facilitator/${facilitatorId}/detail`,
            isActive: false,
          },
          {
            label: "Event Contracts",
            to: `/admin/facilitator/${facilitatorId}/event-contracts`,
            isActive: false,
          },
          {
            label: "Comments",
            to: `/admin/facilitator/${facilitatorId}/comments`,
            isActive: false,
          },
          {
            label: "Attachments",
            to: `/admin/facilitator/${facilitatorId}/attachments`,
            isActive: true,
          },
          {
            label: "More",
            to: `/admin/facilitator/${facilitatorId}/more`,
            icon: EllipsisHorizontalIcon,
            isActive: false,
          },
        ],

        buildActionButtons: (facilitator, facilitatorId, navigate) => [
          {
            variant: "outline",
            onClick: () => navigate("/admin/facilitators"),
            icon: ChevronLeftIcon,
            label: "Back",
          },
          {
            variant: "outline",
            onClick: () => navigate(`/admin/facilitator/${facilitatorId}`),
            icon: ChevronLeftIcon,
            label: "Back to Detail",
          },
        ],

        addPath: `/admin/facilitator/{entityId}/attachments/add`,
        viewPath: `/admin/facilitator/{entityId}/attachment/{id}`,
        editPath: `/admin/facilitator/{entityId}/attachment/{id}/edit`,
        deletePath: `/admin/facilitator/{entityId}/attachment/{id}/delete`,
      },

      buildFieldSections: (facilitator) => {
        if (!facilitator) 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 === FACILITATOR_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>
            ),
          },
          {
            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);
      },

      buildAlerts: (facilitator) => ({
        archived: {
          message: "This facilitator is archived",
          icon: ArchiveBoxIcon,
        },
        banned: { message: "This facilitator is banned", icon: XCircleIcon },
      }),

      canAddAttachments: (facilitator) => {
        return facilitator
          ? facilitator.status !== FACILITATOR_STATUS_ARCHIVED &&
              !facilitator.isBanned
          : false;
      },

      onAttachmentClick,
      onDeleteAttachment,
    }),
    [
      fetchEntity,
      fetchAttachments,
      onAttachmentClick,
      onDeleteAttachment,
      getLevelLabel,
      formatScoreRating,
      extractIds,
    ],
  );

  return <EntityAttachmentListPage config={config} />;
}

export default AdminFacilitatorDetailAttachmentListPage;
