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

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

// Speaker constants
const REPRESENTATIVE_SPEAKER_TYPE_OF_ID = 2;
const INDIVIDUAL_SPEAKER_TYPE_OF_ID = 1;

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

// Helper function to format score rating - now theme-aware
const formatScoreRating = (score, getThemeClasses) => {
  if (!score)
    return (
      <span
        className={`text-sm sm:text-base lg:text-lg ${getThemeClasses("text.muted")}`}
      >
        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)
              ? getThemeClasses("text.accent")
              : getThemeClasses("text.muted")
          }`}
        />
      ))}
      <span
        className={`ml-2 text-sm sm:text-base lg:text-lg ${getThemeClasses("text.secondary")} font-medium`}
      >
        ({score}/5)
      </span>
    </div>
  );
};

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

// Stable empty function to prevent unnecessary re-renders
const emptyFunction = () => {};

function AdminSpeakerDetailAttachmentListPage() {
  const attachmentManager = useAttachmentManager();
  const speakerManager = useSpeakerManager();
  const { getThemeClasses } = useUIXTheme();

  const fetchEntity = useCallback(async (speakerId, onUnauthorized) => {
    return await speakerManager.getSpeakerDetail(speakerId, onUnauthorized);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const fetchAttachments = useCallback(async (params, onUnauthorized) => {
    return await attachmentManager.getAttachments(params, onUnauthorized, true);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

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

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

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

      fetchEntity,
      fetchAttachments,

      attachmentParams: {
        ownershipRole: ATTACHMENT_OWNERSHIP_TYPE.SPEAKER,
      },

      header: {
        title: "Speaker - Attachments",
        icon: PaperClipIcon,
        loadingText: "Loading speaker attachments...",
        notFoundTitle: "Speaker Not Found",
        notFoundMessage:
          "The speaker you're looking for doesn't exist or you don't have permission to view it.",
        notFoundAction: {
          label: "Back to Speakers",
          icon: ChevronLeftIcon,
          onClick: () => (window.location.href = "/admin/speakers"),
        },
      },

      routes: {
        buildBreadcrumbs: (speaker, speakerId) => [
          { label: "Dashboard", to: "/admin/dashboard", icon: HomeIcon },
          { label: "Speakers", to: "/admin/speakers", icon: MicrophoneIcon },
          {
            label:
              speaker?.name ||
              (speaker?.firstName && speaker?.lastName
                ? `${speaker.firstName} ${speaker.lastName}`
                : "Speaker Detail"),
            to: `/admin/speaker/${speakerId}`,
          },
          { label: "Attachments", icon: PaperClipIcon, isActive: true },
        ],

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

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

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

      buildFieldSections: (speaker) => {
        if (!speaker || !speaker.id) return [];

        return [
          {
            type: "avatar",
            component: (
              <Avatar
                src={speaker.avatarObjectUrl}
                alt={
                  speaker.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>
                {speaker.type === REPRESENTATIVE_SPEAKER_TYPE_OF_ID &&
                  speaker.representitiveOrganizationName && (
                    <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`}
                    >
                      <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 ${getThemeClasses("text.primary")}`}
                      />
                      <span className="break-words">
                        {speaker.representitiveOrganizationName}
                      </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`}
                >
                  {speaker.type === INDIVIDUAL_SPEAKER_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 ${getThemeClasses("text.primary")}`}
                    />
                  )}
                  <span className="break-words">
                    {speaker.name || `${speaker.firstName} ${speaker.lastName}`}
                  </span>
                </h3>
                <div
                  className={`mt-2 text-sm lg:text-base ${getThemeClasses("text.secondary")} flex flex-wrap gap-2 justify-center xl:justify-start`}
                >
                  {speaker.level && getLevelLabel(speaker.level) && (
                    <Badge variant="info" size="md">
                      {getLevelLabel(speaker.level)}
                    </Badge>
                  )}
                  {speaker.isBanned ? (
                    <Badge variant="error" size="sm">
                      <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                      Banned
                    </Badge>
                  ) : speaker.status === SPEAKER_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">
                {speaker.skillSets && speaker.skillSets.length > 0 && (
                  <div className="flex flex-wrap gap-2 justify-center xl:justify-start">
                    <SkillSetsDisplay
                      values={extractIds(speaker.skillSets)}
                      onUnauthorized={emptyFunction}
                    />
                  </div>
                )}
              </div>
            ),
          },
          {
            column: "primary",
            className: "mb-3 sm:mb-4 lg:mb-5",
            component: (
              <AddressDisplay
                addressData={speaker}
                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={speaker.email}
                  size="md"
                  fallbackText="No email"
                />
                <ContactLink
                  type="phone"
                  value={speaker.phone}
                  size="md"
                  fallbackText="No phone"
                />
                {speaker.otherPhone && (
                  <ContactLink
                    type="phone"
                    value={speaker.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 ${getThemeClasses("text.secondary")}`}
                  >
                    Type
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {speaker.type === REPRESENTATIVE_SPEAKER_TYPE_OF_ID
                      ? "Representative"
                      : speaker.type === INDIVIDUAL_SPEAKER_TYPE_OF_ID
                        ? "Individual"
                        : "Unassigned"}
                  </p>
                </div>

                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Rating
                  </label>
                  <div className="mt-1">
                    {formatScoreRating(speaker.score, getThemeClasses)}
                  </div>
                </div>
              </div>
            ),
          },
          {
            column: "secondary",
            className: "mb-4 sm:mb-5",
            component: (
              <div>
                <TagsDisplay
                  values={extractIds(speaker.tags)}
                  label="Tags"
                  onUnauthorized={emptyFunction}
                />
              </div>
            ),
          },
          {
            column: "secondary",
            component: (
              <div
                className={`space-y-2 text-xs sm:text-sm lg:text-base ${getThemeClasses("text.secondary")}`}
              >
                {speaker.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(speaker.createdAt)}
                    </span>
                  </div>
                )}
                {speaker.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(speaker.modifiedAt)}
                    </span>
                  </div>
                )}
              </div>
            ),
          },
        ].filter((section) => section.component);
      },

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

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

      onAttachmentClick,
      onDeleteAttachment,
    }),
    [
      fetchEntity,
      fetchAttachments,
      onAttachmentClick,
      onDeleteAttachment,
      getThemeClasses,
    ],
  );

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

export default AdminSpeakerDetailAttachmentListPage;
