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

import React, { useCallback, useMemo } from "react";
import {
  MegaphoneIcon,
  CameraIcon,
  ArchiveBoxIcon,
  ArchiveBoxXMarkIcon,
  TrashIcon,
  LockClosedIcon,
  DevicePhoneMobileIcon,
  NoSymbolIcon,
  CheckCircleIcon,
  ArrowUpCircleIcon,
  ArrowDownCircleIcon,
  EllipsisHorizontalIcon,
  ChartBarIcon,
  XCircleIcon,
  ClockIcon,
  BuildingOfficeIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";
import { StarIcon as StarIconSolid } from "@heroicons/react/24/solid";
import { useSpeakerManager } from "../../../../../services/Services";
import { EntityMorePage } from "../../../../../components/business/views";
import {
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  TagsDisplay,
  SkillSetsDisplay,
} from "../../../../../components/business/displays";
import { formatDateForDisplay } from "../../../../../services/Helpers/DateFormatter";

// Speaker constants
const REPRESENTATIVE_SPEAKER_TYPE_OF_ID = 2;
const INDIVIDUAL_SPEAKER_TYPE_OF_ID = 1;
const RESIDENTIAL_SPEAKER_TYPE_OF_ID = 2; // Residential type
const COMMERCIAL_SPEAKER_TYPE_OF_ID = 3; // Commercial type
const SPEAKER_STATUS_ACTIVE = 1;
const SPEAKER_STATUS_ARCHIVED = 2;

const SPEAKER_CONSTANTS = {
  RESIDENTIAL_SPEAKER_TYPE_OF_ID,
  COMMERCIAL_SPEAKER_TYPE_OF_ID,
  SPEAKER_STATUS_ACTIVE,
  SPEAKER_STATUS_ARCHIVED,
};

// 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);
};

// Function to create tab items for speaker
const createSpeakerTabItems = (speaker, speakerId) => [
  {
    label: "Summary",
    href: `/admin/speaker/${speaker.id}`,
    isActive: false,
  },
  {
    label: "Detail",
    href: `/admin/speaker/${speaker.id}/detail`,
    isActive: false,
  },
  {
    label: "Event Contracts",
    href: `/admin/speaker/${speaker.id}/event-contracts`,
    isActive: false,
  },
  {
    label: "Comments",
    href: `/admin/speaker/${speaker.id}/comments`,
    isActive: false,
  },
  {
    label: "Attachments",
    href: `/admin/speaker/${speaker.id}/attachments`,
    isActive: false,
  },
  {
    label: "More",
    href: `/admin/speaker/${speaker.id}/more`,
    isActive: true,
    icon: EllipsisHorizontalIcon,
  },
];

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

// Function to build field sections for speaker
const buildSpeakerFieldSections = (speaker, getThemeClasses) => {
  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 === 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">
          {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);
};

// Function to create action cards for speaker
const createSpeakerActionCards = (speaker, speakerId, constants) => {
  const actionCards = [];

  if (speaker) {
    // Avatar - Available for all speakers
    actionCards.push({
      key: "avatar",
      title: "Avatar",
      subtitle: "Change the speaker's profile picture",
      icon: CameraIcon,
      path: `/admin/speaker/${speakerId}/avatar`,
      disabled: false,
    });

    // Archive/Unarchive
    if (speaker.status === constants.SPEAKER_STATUS_ARCHIVED) {
      actionCards.push({
        key: "unarchive",
        title: "Unarchive",
        subtitle: "Make speaker visible in list and search results",
        icon: ArchiveBoxXMarkIcon,
        path: `/admin/speaker/${speakerId}/unarchive`,
        disabled: false,
      });
    } else {
      actionCards.push({
        key: "archive",
        title: "Archive",
        subtitle: "Make speaker hidden from list and search results",
        icon: ArchiveBoxIcon,
        path: `/admin/speaker/${speakerId}/archive`,
        disabled: false,
      });
    }

    // Upgrade/Downgrade - Only for active speakers
    if (speaker.status === constants.SPEAKER_STATUS_ACTIVE) {
      if (speaker.type === constants.COMMERCIAL_SPEAKER_TYPE_OF_ID) {
        actionCards.push({
          key: "downgrade",
          title: "Downgrade",
          subtitle: "Change speaker to residential speaker",
          icon: ArrowDownCircleIcon,
          path: `/admin/speaker/${speakerId}/downgrade`,
          disabled: false,
        });
      } else {
        actionCards.push({
          key: "upgrade",
          title: "Upgrade",
          subtitle: "Change speaker to commercial speaker",
          icon: ArrowUpCircleIcon,
          path: `/admin/speaker/${speakerId}/upgrade`,
          disabled: false,
        });
      }

      // Password - Only for active speakers
      actionCards.push({
        key: "password",
        title: "Password",
        subtitle: "Change or reset the speaker's password",
        icon: LockClosedIcon,
        path: `/admin/speaker/${speakerId}/change-password`,
        disabled: false,
      });

      // 2FA - Only for active speakers
      actionCards.push({
        key: "2fa",
        title: "2FA",
        subtitle: "Enable or disable two-factor authentication",
        icon: DevicePhoneMobileIcon,
        path: `/admin/speaker/${speakerId}/change-2fa`,
        disabled: false,
      });

      // Delete - Only for active speakers
      actionCards.push({
        key: "delete",
        title: "Delete",
        subtitle: "Permanently delete this speaker and all related data",
        icon: TrashIcon,
        path: `/admin/speaker/${speakerId}/permadelete`,
        disabled: false,
      });
    }

    // Ban/Unban
    if (speaker.isBanned) {
      actionCards.push({
        key: "unban",
        title: "Unban",
        subtitle: "Remove ban from speaker",
        icon: CheckCircleIcon,
        path: `/admin/speaker/${speakerId}/unban`,
        disabled: false,
      });
    } else {
      actionCards.push({
        key: "ban",
        title: "Ban",
        subtitle: "Mark the speaker as banned",
        icon: NoSymbolIcon,
        path: `/admin/speaker/${speakerId}/ban`,
        disabled: false,
      });
    }
  }

  return actionCards;
};

function AdminSpeakerDetailMorePage() {
  const speakerManager = useSpeakerManager();
  const { getThemeClasses } = useUIXTheme();

  // Custom get speaker detail function wrapped with useCallback to prevent infinite loops
  const getSpeakerDetailWithManager = useCallback(
    async (speakerId, onUnauthorized) => {
      return new Promise((resolve, reject) => {
        speakerManager.getSpeakerDetailWithCallbacks(
          speakerId,
          (speakerData) => resolve(speakerData), // onSuccess
          (error) => reject(error), // onError
          emptyFunction, // onDone
          onUnauthorized, // onUnauthorized
        );
      });
    },
    [speakerManager],
  );

  // Memoize buildFieldSections wrapper to prevent unnecessary re-renders
  const buildFieldSectionsMemo = useCallback(
    (speaker) => {
      return buildSpeakerFieldSections(speaker, getThemeClasses);
    },
    [getThemeClasses],
  );

  return (
    <EntityMorePage
      entityIcon={MegaphoneIcon}
      entityType="Speaker"
      entityTypePlural="Speakers"
      basePath="/admin/speakers"
      entityParamName="aid"
      entityManager={speakerManager}
      getEntityDetail={getSpeakerDetailWithManager}
      createTabItems={createSpeakerTabItems}
      createActionCards={createSpeakerActionCards}
      constants={SPEAKER_CONSTANTS}
      infoMessage="Some actions are only available for active speakers. Archived speakers must be unarchived first before performing other actions."
      buildFieldSections={buildFieldSectionsMemo}
    />
  );
}

export default AdminSpeakerDetailMorePage;
