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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useParams } from "react-router";
import {
  useEventOrderManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  DetailLiteView,
  Badge,
  ContactLink,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  TicketIcon,
  UserIcon,
  CalendarIcon,
  ClockIcon,
  ChevronLeftIcon,
  InformationCircleIcon,
  PencilSquareIcon,
  BuildingOfficeIcon,
  EllipsisHorizontalIcon,
  DocumentTextIcon,
  ChatBubbleLeftRightIcon,
  PaperClipIcon,
  HomeIcon,
  ArchiveBoxIcon,
  NoSymbolIcon,
  ClipboardDocumentListIcon,
  ArrowRightIcon,
} from "@heroicons/react/24/outline";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";
import {
  getEventOrderStatusLabel,
  getEventOrderStatusVariant,
} from "../../../../constants/EventOrder";
import {
  TASK_ITEM_TYPE,
  TASK_ITEM_STATUS,
} from "../../../../constants/Task";

function AdminEventOrderLitePage() {
  const navigate = useNavigate();
  const { eventOrderID } = useParams();
  const eventOrderManager = useEventOrderManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

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

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

  const handleBackToOrders = useCallback(() => {
    navigate("/admin/event-orders");
  }, [navigate]);

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

  // Helper function to get task route based on task type
  const getTaskRoute = useCallback((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.CREATE_EVENT_CONTRACT]: `/admin/task/${taskId}/create-event-contract`,
      [TASK_ITEM_TYPE.ASSIGN_FACILITATOR]: `/admin/task/${taskId}/assign-facilitator`,
      [TASK_ITEM_TYPE.ASSIGN_SPEAKER]: `/admin/task/${taskId}/assign-speaker`,
      [TASK_ITEM_TYPE.REVIEW_EVENT_CONTRACT]: `/admin/task/${taskId}/review-event-contract`,
      [TASK_ITEM_TYPE.PAY_EVENT_CONTRACT]: `/admin/task/${taskId}/pay-event-contract`,
      [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]: `/admin/task/${taskId}/collect-payment`,
      [TASK_ITEM_TYPE.SURVEY_EVENT_ORDER]: `/admin/task/${taskId}/survey-event-order`,
      [TASK_ITEM_TYPE.SEND_CERTIFICATE]: `/admin/task/${taskId}/send-certificate`,
    };

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

  // Helper function to get task type label
  const getTaskTypeLabel = useCallback((taskType) => {
    const labelMap = {
      [TASK_ITEM_TYPE.CLOSE_EVENT]: "Close Event",
      [TASK_ITEM_TYPE.CREATE_EVENT_ORDER]: "Create Event Order",
      [TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT]: "Create Event Contract",
      [TASK_ITEM_TYPE.ASSIGN_FACILITATOR]: "Assign Facilitator",
      [TASK_ITEM_TYPE.ASSIGN_SPEAKER]: "Assign Speaker",
      [TASK_ITEM_TYPE.REVIEW_EVENT_CONTRACT]: "Review Event Contract",
      [TASK_ITEM_TYPE.PAY_EVENT_CONTRACT]: "Pay Event Contract",
      [TASK_ITEM_TYPE.CLOSE_EVENT_ORDER]: "Close Event Order",
      [TASK_ITEM_TYPE.REVIEW_EVENT_ORDER]: "Review Event Order",
      [TASK_ITEM_TYPE.COLLECT_PAYMENT]: "Collect Payment",
      [TASK_ITEM_TYPE.SURVEY_EVENT_ORDER]: "Survey Event Order",
      [TASK_ITEM_TYPE.SEND_CERTIFICATE]: "Send Certificate",
    };

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

  // Load event order data on mount
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    const fetchEventOrder = async () => {
      if (!eventOrderID) {
        setErrors({ general: "Event Order ID is required" });
        setLoading(false);
        return;
      }

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

        const eventOrderData = await eventOrderManager.getEventOrderDetail(
          eventOrderID,
          onUnauthorized,
        );

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

    fetchEventOrder();
  }, [eventOrderID, eventOrderManager, authManager, navigate, onUnauthorized]);

  // Create status badge component
  const createStatusBadge = useCallback((order) => {
    if (!order) return null;
    const statusLabel = getEventOrderStatusLabel(order.status);
    const statusVariant = getEventOrderStatusVariant(order.status);

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

  // Configure DetailLiteView props
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Event Orders",
      to: "/admin/event-orders",
      icon: TicketIcon,
    },
    {
      label: `Order #${eventOrder?.publicId || eventOrderID}`,
      icon: InformationCircleIcon,
      isActive: true,
    },
  ];

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

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

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

  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 text-gray-800 flex items-center justify-center xl:justify-start">
            <span className="break-words">
              Event Order #{eventOrder?.publicId || eventOrderID}
            </span>
          </h3>
          <div className="mt-2 text-sm lg:text-base ${getThemeClasses('text.secondary')} flex flex-wrap gap-2 justify-center xl:justify-start">
            <Badge variant="info" size="md">
              ID: #{eventOrder?.id}
            </Badge>
            {createStatusBadge(eventOrder)}
          </div>
        </div>
      ),
    },
    {
      column: "primary",
      className: "mb-3 sm:mb-4 lg:mb-5",
      component: eventOrder?.customerId ? (
        <div className="space-y-2 sm:space-y-3">
          <div>
            <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
              Customer
            </label>
            <p className="text-base ${getThemeClasses('text.primary')} mt-1 flex items-center">
              <UserIcon className="w-4 h-4 mr-2" />
              {eventOrder.customerName ||
                `${eventOrder.customerFirstName || ""} ${eventOrder.customerLastName || ""}`.trim() ||
                "Customer Name Not Available"}
            </p>
          </div>
          <ContactLink
            type="email"
            value={eventOrder.customerEmail}
            size="md"
            fallbackText="No email provided"
          />
        </div>
      ) : (
        <div className="text-sm text-gray-500">
          No customer information available
        </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">
              {eventOrder?.eventName || "Event information not available"}
            </p>
          </div>

          {eventOrder?.eventStartDateTime && (
            <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(eventOrder.eventStartDateTime)}
              </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(eventOrder?.createdAt)}
            </p>
          </div>

          {/* Latest Task */}
          {eventOrder?.latestTaskItemId && (eventOrder?.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE || eventOrder?.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING) && (
            <div>
              <label className="text-sm font-medium text-gray-600 mb-2 block">
                Latest Task
              </label>
              <button
                onClick={() => eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE ? navigate(getTaskRoute(eventOrder.latestTaskItemType, eventOrder.latestTaskItemId)) : null}
                disabled={eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING}
                className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
                  eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING
                    ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                    : 'bg-blue-600 text-white hover:bg-blue-700'
                }`}
              >
                <ClipboardDocumentListIcon className="w-4 h-4" />
                <span>{getTaskTypeLabel(eventOrder.latestTaskItemType)}</span>
                {eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING && (
                  <Badge variant="warning" size="sm">Locked</Badge>
                )}
                {eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE && (
                  <ArrowRightIcon className="w-4 h-4" />
                )}
              </button>
            </div>
          )}
        </div>
      ),
    },
  ], [eventOrder, eventOrderID, createStatusBadge, navigate, getTaskRoute, getTaskTypeLabel]); // getThemeClasses removed - captured in closure

  const alerts = {
    archived: {
      message: "This event order is archived",
      icon: ArchiveBoxIcon,
    },
    banned: {
      message: "This event order has issues",
      icon: NoSymbolIcon,
    },
  };

  return (
    <DetailLiteView
      entityData={eventOrder}
      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 AdminEventOrderLitePage;
