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

import React, { useState, useEffect, useMemo, useCallback } 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 {
  useFacilitatorManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  TagsDisplay,
  SkillSetsDisplay,
  CertificationDisplay,
  SpecializationDisplay,
} from "../../../../components/business/displays";
import {
  DetailLiteView,
  Badge,
  ContactLink,
  AddressDisplay,
  Button,
} from "../../../../components/UIX";

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

function AdminFacilitatorDetailLitePage() {
  const { aid } = useParams();
  const facilitatorManager = useFacilitatorManager();
  const authManager = useAuthManager();
  const navigate = useNavigate();

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

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

  // Fetch facilitator detail
  const fetchFacilitatorDetail = useCallback(
    async (facilitatorId) => {
      try {
        setFetching(true);
        setErrors({});

        const response = await facilitatorManager.getFacilitatorDetail(
          facilitatorId,
          onUnauthorized,
        );
        setFacilitator(response);
      } catch (error) {
        console.error("Failed to fetch facilitator detail:", error);
        setErrors(error);
      } finally {
        setFetching(false);
      }
    },
    [facilitatorManager, onUnauthorized],
  );

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

    if (aid) {
      fetchFacilitatorDetail(aid);
    }
  }, [aid, authManager, navigate, fetchFacilitatorDetail]);

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

  // Create status badge component
  const createStatusBadge = useCallback((facilitator) => {
    if (!facilitator) return null;
    if (facilitator.isBanned) {
      return (
        <Badge variant="error" size="sm">
          <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
          Banned
        </Badge>
      );
    }
    if (facilitator.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>
    );
  }, []);

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

  // Format score rating
  const formatScoreRating = useCallback((score) => {
    if (!score)
      return (
        <span className="text-gray-500 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 text-gray-600 font-medium">
          ({score}/5)
        </span>
      </div>
    );
  }, []);

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

  // Configure DetailLiteView props (must be before conditional returns)
  const breadcrumbItems = useMemo(
    () => [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: HomeIcon,
      },
      {
        label: "Facilitators",
        to: "/admin/facilitators",
        icon: UserGroupIcon,
      },
      {
        label: "Detail",
        icon: InformationCircleIcon,
        isActive: true,
      },
    ],
    [],
  );

  const headerConfig = useMemo(
    () => ({
      title: "Facilitator - Summary",
      icon: UserGroupIcon,
      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: () => navigate("/admin/facilitators"),
      },
    }),
    [navigate],
  );

  const actionButtons = useMemo(
    () => [
      {
        variant: "outline",
        onClick: () => navigate("/admin/facilitators"),
        icon: ChevronLeftIcon,
        label: "Back",
      },
      {
        variant: "secondary",
        onClick: () => navigate(`/admin/facilitator/${aid}/edit`),
        icon: PencilSquareIcon,
        label: "Edit",
        disabled: facilitator.status === 2,
      },
    ],
    [navigate, aid, facilitator.status],
  );

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

  const fieldSections = useMemo(
    () => [
      // Avatar section
      {
        type: "avatar",
        component: (
          <img
            src={
              facilitator.avatarObjectUrl && facilitator.avatarObjectUrl !== ""
                ? facilitator.avatarObjectUrl
                : "/img/placeholder.png"
            }
            alt={
              facilitator.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>
            {facilitator.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID &&
              facilitator.representitiveOrganizationName && (
                <h2 className="text-lg sm:text-xl md:text-2xl lg:text-3xl font-bold text-gray-900 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">
                    {facilitator.representitiveOrganizationName}
                  </span>
                </h2>
              )}
            <h3 className="text-base sm:text-lg md:text-xl lg:text-2xl font-semibold text-gray-800 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 ${getThemeClasses('text-accent')} flex-shrink-0`} />
              )}
              <span className="break-words">
                {getFacilitatorDisplayName(facilitator)}
              </span>
            </h3>
            <div className="mt-2 text-sm lg:text-base text-gray-600 flex flex-wrap gap-2 justify-center xl:justify-start">
              {facilitator.level && getLevelLabel(facilitator.level) && (
                <Badge variant="info" size="md">
                  {getLevelLabel(facilitator.level)}
                </Badge>
              )}
              {createStatusBadge(facilitator)}
            </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={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={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 provided"
            />
            <ContactLink
              type="phone"
              value={facilitator?.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 text-gray-600">Type</label>
              <p className="text-base text-gray-900 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 text-gray-600">
                Rating
              </label>
              <div className="mt-1">{formatScoreRating(facilitator.score)}</div>
            </div>
          </div>
        ),
      },
      {
        column: "secondary",
        className: "mb-4 sm:mb-5",
        component: (
          <div>
            <TagsDisplay
              values={extractIds(facilitator.tags)}
              label="Tags"
              onUnauthorized={onUnauthorized}
            />
          </div>
        ),
      },
    ],
    [
      facilitator,
      getFacilitatorDisplayName,
      getLevelLabel,
      createStatusBadge,
      extractIds,
      onUnauthorized,
      formatScoreRating,
    ],
  );

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

  return (
    <DetailLiteView
      entityData={facilitator}
      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={() => setErrors({})}
    />
  );
}

export default AdminFacilitatorDetailLitePage;
