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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useParams } from "react-router";
import {
  UserGroupIcon,
  InformationCircleIcon,
  PencilSquareIcon,
  ChevronLeftIcon,
  EnvelopeIcon,
  PhoneIcon,
  StarIcon,
  MapPinIcon,
  BuildingOfficeIcon,
  HomeIcon,
  CheckCircleIcon,
  XCircleIcon,
  NoSymbolIcon,
  ArchiveBoxIcon,
  ArrowTopRightOnSquareIcon,
  EllipsisHorizontalIcon,
} from "@heroicons/react/24/outline";
import { StarIcon as StarIconSolid } from "@heroicons/react/24/solid";
import {
  useSpeakerManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  TagsDisplay,
  SkillSetsDisplay,
  CertificationDisplay,
  SpecializationDisplay,
} from "../../../../components/business/displays";
import {
  DetailLiteView,
  Badge,
  ContactLink,
  AddressDisplay,
  Button,
  useUIXTheme,
} from "../../../../components/UIX";

// Constants
const REPRESENTATIVE_SPEAKER_TYPE_OF_ID = 2;
const INDIVIDUAL_SPEAKER_TYPE_OF_ID = 1;
const SPEAKER_IS_JOB_SEEKER_YES = 1;

function AdminSpeakerDetailLitePage() {
  const { id } = useParams();
  const speakerManager = useSpeakerManager();
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [speaker, setSpeaker] = useState({});

  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Fetch speaker detail
  const fetchSpeakerDetail = useCallback(
    async (speakerId) => {
      try {
        setFetching(true);
        setErrors({});

        const response = await speakerManager.getSpeakerDetail(
          speakerId,
          onUnauthorized,
        );
        setSpeaker(response);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Failed to fetch speaker detail:", error);
        }
        setErrors(error);
      } finally {
        setFetching(false);
      }
    },
    [speakerManager, onUnauthorized],
  );

  // Lifecycle
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    if (id) {
      fetchSpeakerDetail(id);
    }
  }, [id, authManager, navigate, fetchSpeakerDetail]);

  // Helper function to get speaker display name
  const getSpeakerDisplayName = useCallback((speaker) => {
    if (!speaker) return "Speaker";
    if (
      speaker.type === REPRESENTATIVE_SPEAKER_TYPE_OF_ID &&
      speaker.representitiveOrganizationName
    ) {
      return speaker.representitiveOrganizationName;
    }
    if (speaker.name) return speaker.name;
    const fullName =
      `${speaker.firstName || ""} ${speaker.lastName || ""}`.trim();
    return fullName || "Speaker";
  }, []);

  // Create status badge component
  const createStatusBadge = useCallback((speaker) => {
    if (!speaker) return null;
    if (speaker.isBanned) {
      return (
        <Badge variant="error" size="sm">
          <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
          Banned
        </Badge>
      );
    }
    if (speaker.status === 1) {
      return (
        <Badge variant="primary" size="sm">
          <CheckCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
          Active
        </Badge>
      );
    }
    return (
      <Badge variant="secondary" size="sm">
        <ArchiveBoxIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
        Archived
      </Badge>
    );
  }, []);

  // Format score rating
  const formatScoreRating = useCallback(
    (score) => {
      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>
      );
    },
    [getThemeClasses],
  );

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

  // Helper function to get speaker level label
  const getLevelLabel = useCallback((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;
    }
  }, []);

  // Navigation callbacks - extracted to prevent recreating on every render
  const handleBackToSpeakers = useCallback(() => {
    navigate("/admin/speakers");
  }, [navigate]);

  const handleEditSpeaker = useCallback(() => {
    navigate(`/admin/speaker/${id}/edit`);
  }, [navigate, id]);

  const handleErrorClose = useCallback(() => {
    setErrors({});
  }, []);

  // Configure DetailLiteView props - MUST be before early returns to follow Rules of Hooks
  const breadcrumbItems = useMemo(
    () => [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: HomeIcon,
      },
      {
        label: "Speakers",
        to: "/admin/speakers",
        icon: UserGroupIcon,
      },
      {
        label: "Detail",
        icon: InformationCircleIcon,
        isActive: true,
      },
    ],
    [],
  );

  const headerConfig = useMemo(
    () => ({
      title: "Speaker - Summary",
      icon: UserGroupIcon,
      loadingText: "Loading speaker details...",
      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: handleBackToSpeakers,
      },
    }),
    [handleBackToSpeakers],
  );

  const actionButtons = useMemo(
    () => [
      {
        variant: "outline",
        onClick: handleBackToSpeakers,
        icon: ChevronLeftIcon,
        label: "Back",
      },
      {
        variant: "secondary",
        onClick: handleEditSpeaker,
        icon: PencilSquareIcon,
        label: "Edit",
        disabled: speaker.status === 2,
      },
    ],
    [handleBackToSpeakers, handleEditSpeaker, speaker.status],
  );

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

  const fieldSections = useMemo(
    () => [
      // Avatar section
      {
        type: "avatar",
        component: (
          <img
            src={
              speaker.avatarObjectUrl && speaker.avatarObjectUrl !== ""
                ? speaker.avatarObjectUrl
                : "/img/placeholder.png"
            }
            alt={
              speaker.avatarObjectUrl ? "Profile Picture" : "No Profile Picture"
            }
            className={`w-20 h-20 sm:w-28 sm:h-28 md:w-32 md:h-32 lg:w-36 lg:h-36 xl:w-40 xl:h-40 rounded-2xl object-cover border-2 ${getThemeClasses("border-border")} shadow-sm mx-auto xl:mx-0`}
          />
        ),
      },
      // Primary column sections
      {
        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 ${getThemeClasses("text-accent")} flex-shrink-0`}
                  />
                  <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 ${getThemeClasses("text-accent")} flex-shrink-0`}
                />
              )}
              <span className="break-words">
                {getSpeakerDisplayName(speaker)}
              </span>
            </h3>
            {speaker.level && getLevelLabel(speaker.level) && (
              <div className="mt-2 text-sm lg:text-base flex flex-wrap gap-2 justify-center xl:justify-start">
                <Badge variant="info" size="md">
                  {getLevelLabel(speaker.level)}
                </Badge>
              </div>
            )}
            <div
              className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} flex flex-wrap gap-2 justify-center xl:justify-start`}
            >
              {createStatusBadge(speaker)}
            </div>
            {speaker.skillSets && speaker.skillSets.length > 0 && (
              <div className="mt-2 flex flex-wrap gap-2 justify-center xl:justify-start">
                <SkillSetsDisplay
                  values={extractIds(speaker.skillSets)}
                  onUnauthorized={onUnauthorized}
                />
              </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 provided"
            />
            <ContactLink
              type="phone"
              value={speaker?.phone}
              size="md"
              fallbackText="No phone provided"
            />
          </div>
        ),
      },
      // Secondary column sections
      {
        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)}</div>
            </div>
          </div>
        ),
      },
      {
        column: "secondary",
        className: "mb-4 sm:mb-5",
        component: (
          <div>
            <TagsDisplay
              values={extractIds(speaker.tags)}
              label="Tags"
              onUnauthorized={onUnauthorized}
            />
          </div>
        ),
      },
    ],
    [
      speaker,
      getThemeClasses,
      getSpeakerDisplayName,
      getLevelLabel,
      createStatusBadge,
      extractIds,
      formatScoreRating,
      onUnauthorized,
    ],
  );

  const alerts = useMemo(
    () => ({
      archived: {
        message: "This speaker is archived",
        icon: ArchiveBoxIcon,
      },
      banned: {
        message: "This speaker is banned",
        icon: NoSymbolIcon,
      },
    }),
    [],
  );

  // Early returns AFTER all hooks to comply with Rules of Hooks
  if (!authManager.isAuthenticated()) {
    return (
      <DetailLiteView
        isLoading={true}
        headerConfig={{
          loadingText: "Checking authentication...",
        }}
      />
    );
  }

  if (isFetching && !speaker.id) {
    return (
      <DetailLiteView
        isLoading={isFetching}
        headerConfig={{
          loadingText: "Loading speaker summary...",
        }}
      />
    );
  }

  return (
    <DetailLiteView
      entityData={speaker}
      breadcrumbItems={breadcrumbItems}
      headerConfig={headerConfig}
      fieldSections={fieldSections}
      actionButtons={actionButtons}
      tabs={tabs}
      alerts={alerts}
      onUnauthorized={onUnauthorized}
      isLoading={isFetching}
      error={
        errors && typeof errors === "object" && Object.keys(errors).length > 0
          ? Object.entries(errors)
              .map(
                ([key, value]) =>
                  `${key}: ${Array.isArray(value) ? value.join(", ") : value}`,
              )
              .join("; ")
          : null
      }
      onErrorClose={handleErrorClose}
    />
  );
}

export default AdminSpeakerDetailLitePage;
