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

import React, { useState, useEffect, useMemo, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import {
  useEventContractManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  DetailLiteView,
  Badge,
  ContactLink,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  DocumentCheckIcon,
  UserIcon,
  CalendarIcon,
  ClockIcon,
  ChevronLeftIcon,
  InformationCircleIcon,
  PencilSquareIcon,
  BuildingOfficeIcon,
  EllipsisHorizontalIcon,
  DocumentTextIcon,
  ChatBubbleLeftRightIcon,
  PaperClipIcon,
  HomeIcon,
  ArchiveBoxIcon,
  NoSymbolIcon,
  UserGroupIcon,
  ClipboardDocumentListIcon,
  ArrowRightIcon,
} from "@heroicons/react/24/outline";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";
import {
  getEventContractStatusLabel,
  getEventContractStatusVariant,
} from "../../../../constants/EventContract";
import {
  EVENT_TYPE_CONFERENCE,
  EVENT_TYPE_ONSITE,
  EVENT_TYPE_OFFSITE,
  EVENT_TYPE_VIRTUAL,
} from "../../../../constants/Event";
import {
  TASK_ITEM_TYPE,
  TASK_ITEM_STATUS,
} from "../../../../constants/Task";

/**
 * Helper function to get task route based on task type
 * Maps task types to their corresponding route patterns
 */
const getTaskRoute = (taskType, taskId) => {
  if (!taskId) return null;

  const routeMap = {
    [TASK_ITEM_TYPE.CLOSE_EVENT]: `/admin/task/${taskId}/close-event`,
    [TASK_ITEM_TYPE.CREATE_EVENT_ORDER]: `/admin/task/${taskId}/create-event-order`,
    [TASK_ITEM_TYPE.CLOSE_EVENT_ORDER]: `/admin/task/${taskId}/close-event-order`,
    [TASK_ITEM_TYPE.REVIEW_EVENT_ORDER]: `/admin/task/${taskId}/review-event-order`,
    [TASK_ITEM_TYPE.COLLECT_PAYMENT_FOR_EVENT_ORDER]: `/admin/task/${taskId}/collect-payment-for-event-order`,
    [TASK_ITEM_TYPE.SURVEY_CLIENT_FOR_EVENT_ORDER]: `/admin/task/${taskId}/client-survey-for-event-order`,
    [TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT]: `/admin/task/${taskId}/create-event-contract`,
    [TASK_ITEM_TYPE.ASSIGN_FACILITATOR_OR_SPEAKER_TO_EVENT]: `/admin/task/${taskId}`,
    [TASK_ITEM_TYPE.CLOSE_EVENT_CONTRACT]: `/admin/task/${taskId}/close-event-contract`,
    [TASK_ITEM_TYPE.EVENT_CONTRACT_REVIEW]: `/admin/task/${taskId}/review-event-contract`,
    [TASK_ITEM_TYPE.PAY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: `/admin/task/${taskId}/pay-facilitator-or-speaker-for-event-contract`,
    [TASK_ITEM_TYPE.SURVEY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: `/admin/task/${taskId}/survey-facilitator-or-speaker-for-event-contract`,
  };

  return routeMap[taskType] || `/admin/task/${taskId}`;
};

/**
 * Helper function to get task type label
 */
const getTaskTypeLabel = (taskType) => {
  const labelMap = {
    [TASK_ITEM_TYPE.CLOSE_EVENT]: "Close Event",
    [TASK_ITEM_TYPE.CREATE_EVENT_ORDER]: "Create Event Order",
    [TASK_ITEM_TYPE.CLOSE_EVENT_ORDER]: "Close Event Order",
    [TASK_ITEM_TYPE.REVIEW_EVENT_ORDER]: "Review Event Order",
    [TASK_ITEM_TYPE.COLLECT_PAYMENT_FOR_EVENT_ORDER]: "Collect Payment for Event Order",
    [TASK_ITEM_TYPE.SURVEY_CLIENT_FOR_EVENT_ORDER]: "Survey Client for Event Order",
    [TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT]: "Create Event Contract",
    [TASK_ITEM_TYPE.ASSIGN_FACILITATOR_OR_SPEAKER_TO_EVENT]: "Assign Facilitator/Speaker",
    [TASK_ITEM_TYPE.CLOSE_EVENT_CONTRACT]: "Close Event Contract",
    [TASK_ITEM_TYPE.EVENT_CONTRACT_REVIEW]: "Review Event Contract",
    [TASK_ITEM_TYPE.PAY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: "Pay Facilitator/Speaker",
    [TASK_ITEM_TYPE.SURVEY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: "Survey Facilitator/Speaker",
  };

  return labelMap[taskType] || "View Task";
};

// Helper function to get event type label
const getEventTypeLabel = (eventType) => {
  // Convert to number in case it comes as a string
  const typeNum =
    typeof eventType === "string" ? parseInt(eventType, 10) : eventType;

  switch (typeNum) {
    case EVENT_TYPE_CONFERENCE:
      return "Conference";
    case EVENT_TYPE_ONSITE:
      return "Onsite";
    case EVENT_TYPE_OFFSITE:
      return "Offsite";
    case EVENT_TYPE_VIRTUAL:
      return "Virtual";
    default:
      return "";
  }
};

function AdminEventContractLitePage() {
  const navigate = useNavigate();
  const { eventContractID } = useParams();
  const eventContractManager = useEventContractManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

  // State management
  const [eventContract, setEventContract] = useState(null);
  const [loading, setLoading] = useState(true);
  const [errors, setErrors] = useState({});

  // Handle unauthorized access - memoized to prevent recreating
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Stable navigation callbacks
  const handleBackToContracts = useCallback(() => {
    navigate("/admin/event-contracts");
  }, [navigate]);

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

  // Load event contract data on mount - FIXED: removed manager dependencies to prevent infinite loop
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    const fetchEventContract = async () => {
      if (!eventContractID) {
        setErrors({ general: "Event Contract ID is required" });
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        setErrors({});

        const eventContractData =
          await eventContractManager.getEventContractDetail(
            eventContractID,
            onUnauthorized,
          );

        setEventContract(eventContractData);
      } catch (err) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to load event contract:", err);
        }
        setErrors(err);
      } finally {
        setLoading(false);
      }
    };

    fetchEventContract();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [eventContractID]); // Only re-fetch when ID changes

  // Create status badge component - memoized to prevent recreating
  const createStatusBadge = useCallback((contract) => {
    if (!contract) return null;
    const statusLabel = getEventContractStatusLabel(contract.status);
    const statusVariant = getEventContractStatusVariant(contract.status);

    return (
      <Badge variant={statusVariant} size="sm">
        {statusLabel}
      </Badge>
    );
  }, []);

  // Configure DetailLiteView props - memoized to prevent recreating on every render
  const breadcrumbItems = useMemo(
    () => [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: HomeIcon,
      },
      {
        label: "Event Contracts",
        to: "/admin/event-contracts",
        icon: DocumentCheckIcon,
      },
      {
        label: `Contract #${eventContract?.publicId || eventContractID}`,
        icon: InformationCircleIcon,
        isActive: true,
      },
    ],
    [eventContract?.publicId, eventContractID],
  );

  const headerConfig = useMemo(
    () => ({
      title: `Event Contract - Summary`,
      icon: DocumentCheckIcon,
      loadingText: "Loading event contract details...",
      notFoundTitle: "Event Contract Not Found",
      notFoundMessage:
        "The event contract you're looking for doesn't exist or you don't have permission to view it.",
      notFoundAction: {
        label: "Back to Event Contracts",
        icon: ChevronLeftIcon,
        onClick: handleBackToContracts,
      },
    }),
    [handleBackToContracts],
  );

  const actionButtons = useMemo(
    () => [
      {
        variant: "outline",
        onClick: handleBackToContracts,
        icon: ChevronLeftIcon,
        label: "Back",
      },
    ],
    [handleBackToContracts],
  );

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

  const fieldSections = useMemo(
    () => [
      // Primary column sections
      {
        column: "primary",
        className: "mb-3 sm:mb-4 lg:mb-5",
        component: (
          <div>
            <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`}
            >
              <span className="break-words">
                {eventContract?.event?.name ||
                  eventContract?.eventName ||
                  "Event Contract"}
              </span>
            </h3>

            {/* Event Type */}
            {eventContract?.eventType > 0 && (
              <div className="mt-2 text-center xl:text-left">
                <span
                  className={`text-sm font-bold ${getThemeClasses("text.secondary")}`}
                >
                  {getEventTypeLabel(eventContract.eventType)}
                </span>
              </div>
            )}

            {/* Event Category */}
            {eventContract?.eventCategory?.name && (
              <div className="mt-2 text-center xl:text-left">
                <span
                  className={`text-sm font-bold ${getThemeClasses("text.primary")}`}
                >
                  {eventContract.eventCategory.name}
                </span>
              </div>
            )}

            {/* Skills, Certifications, and Specializations Pills */}
            {(eventContract?.certifications?.length > 0 ||
              eventContract?.specializations?.length > 0 ||
              eventContract?.eventSkillSets?.length > 0 ||
              eventContract?.facilitatorSkillSets?.length > 0 ||
              eventContract?.speakerSkillSets?.length > 0) && (
              <div className="mt-3 flex flex-wrap gap-2 justify-center xl:justify-start">
                {eventContract?.certifications?.map((cert) => (
                  <Badge key={cert.id} variant="secondary" size="sm">
                    {cert.name}
                  </Badge>
                ))}
                {eventContract?.specializations?.map((spec) => (
                  <Badge key={spec.id} variant="info" size="sm">
                    {spec.name}
                  </Badge>
                ))}
                {eventContract?.eventSkillSets?.map((skill) => (
                  <Badge key={`event-${skill.id}`} variant="success" size="sm">
                    {skill.subCategory ||
                      skill.category ||
                      skill.description ||
                      "Skill Set"}
                  </Badge>
                ))}
                {eventContract?.facilitatorSkillSets?.map((skill) => (
                  <Badge
                    key={`facilitator-${skill.id}`}
                    variant="success"
                    size="sm"
                  >
                    {skill.subCategory ||
                      skill.category ||
                      skill.description ||
                      "Skill Set"}
                  </Badge>
                ))}
                {eventContract?.speakerSkillSets?.map((skill) => (
                  <Badge
                    key={`speaker-${skill.id}`}
                    variant="success"
                    size="sm"
                  >
                    {skill.subCategory ||
                      skill.category ||
                      skill.description ||
                      "Skill Set"}
                  </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(eventContract)}
            </div>

            {/* Date, Time, and Attendees Information */}
            <div className="mt-4 space-y-2 text-center xl:text-left">
              {/* Date and Time Range */}
              {(eventContract?.eventStartDateTime ||
                eventContract?.eventEndDateTime) && (
                <div
                  className={`flex items-center justify-center xl:justify-start text-sm ${getThemeClasses("text.secondary")}`}
                >
                  <CalendarIcon
                    className={`w-4 h-4 mr-2 ${getThemeClasses("text.muted")}`}
                  />
                  <span>
                    {eventContract.eventStartDateTime &&
                    eventContract.eventEndDateTime
                      ? `${eventContract.eventStartDateTime} - ${eventContract.eventEndDateTime}`
                      : eventContract.eventStartDateTime ||
                        eventContract.eventEndDateTime}
                  </span>
                </div>
              )}

              {/* Attendees */}
              {eventContract?.eventAttendeeCapacity && (
                <div
                  className={`flex items-center justify-center xl:justify-start text-sm ${getThemeClasses("text.secondary")}`}
                >
                  <UserGroupIcon
                    className={`w-4 h-4 mr-2 ${getThemeClasses("text.muted")}`}
                  />
                  <span>{eventContract.eventAttendeeCapacity} attendees</span>
                </div>
              )}
            </div>
          </div>
        ),
      },
      {
        column: "primary",
        className: "mb-3 sm:mb-4 lg:mb-5",
        component: (
          <div className="space-y-2 sm:space-y-3">
            <div>
              <p
                className={`text-base ${getThemeClasses("text.primary")} flex items-center`}
              >
                <UserIcon className="w-4 h-4 mr-2" />
                <span className="font-medium">Facilitator:</span>
                <span className="ml-2">
                  {eventContract?.facilitator
                    ? eventContract.facilitator.name ||
                      `${eventContract.facilitator.firstName} ${eventContract.facilitator.lastName}`.trim()
                    : "—"}
                </span>
              </p>
            </div>
            {eventContract?.facilitator && (
              <ContactLink
                type="email"
                value={eventContract.facilitator?.email}
                size="md"
                fallbackText="No email provided"
              />
            )}
            <div>
              <p
                className={`text-base ${getThemeClasses("text.primary")} flex items-center`}
              >
                <ClockIcon className="w-4 h-4 mr-2" />
                <span className="font-medium">Hours:</span>
                <span className="ml-2">
                  {eventContract?.estimatedContractHours || "—"}
                </span>
              </p>
            </div>

            {/* Latest Task */}
            {eventContract?.latestTaskItemId && (eventContract?.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE || eventContract?.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING) && (
              <div className="mt-4">
                <p className={`text-sm font-medium ${getThemeClasses("text.secondary")} mb-2`}>
                  Latest Task
                </p>
                <button
                  onClick={() => eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE ? navigate(getTaskRoute(eventContract.latestTaskItemType, eventContract.latestTaskItemId)) : null}
                  disabled={eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING}
                  className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
                    eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING
                      ? `${getThemeClasses("bg-muted")} ${getThemeClasses("text-muted")} cursor-not-allowed`
                      : `${getThemeClasses("bg-primary")} ${getThemeClasses("text-white")} hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 ${getThemeClasses("focus-ring")}`
                  }`}
                >
                  <ClipboardDocumentListIcon className="w-4 h-4" />
                  <span>{getTaskTypeLabel(eventContract.latestTaskItemType)}</span>
                  {eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING && (
                    <Badge variant="warning" size="sm">Locked</Badge>
                  )}
                  {eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE && (
                    <ArrowRightIcon className="w-4 h-4" />
                  )}
                </button>
              </div>
            )}
          </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")}`}
              >
                Event
              </label>
              <p
                className={`text-base ${getThemeClasses("text.primary")} mt-1`}
              >
                {eventContract?.event?.name ||
                  "Event information not available"}
              </p>
            </div>

            {eventContract?.event?.startDate && (
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                >
                  Event Date
                </label>
                <p
                  className={`text-base ${getThemeClasses("text.primary")} mt-1 flex items-center`}
                >
                  <CalendarIcon className="w-4 h-4 mr-1" />
                  {formatDateForDisplay(eventContract.event.startDate)}
                </p>
              </div>
            )}

            <div>
              <label
                className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
              >
                Created
              </label>
              <p
                className={`text-base ${getThemeClasses("text.primary")} mt-1 flex items-center`}
              >
                <ClockIcon className="w-4 h-4 mr-1" />
                {formatDateForDisplay(eventContract?.createdAt)}
              </p>
            </div>
          </div>
        ),
      },
    ],
    [eventContract, createStatusBadge, getThemeClasses],
  );

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

  return (
    <DetailLiteView
      entityData={eventContract}
      breadcrumbItems={breadcrumbItems}
      headerConfig={headerConfig}
      fieldSections={fieldSections}
      actionButtons={actionButtons}
      tabs={tabs}
      alerts={alerts}
      onUnauthorized={onUnauthorized}
      isLoading={loading}
      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 AdminEventContractLitePage;
