// File Path: monorepo/web/frontend/src/pages/Admin/Event/InSchool/Detail/Order/List/Page.jsx

import React, { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
  AcademicCapIcon,
  ChevronLeftIcon,
  ArrowPathIcon,
  ClockIcon,
  ArchiveBoxIcon,
  ShoppingCartIcon,
  HomeIcon,
  ArrowRightIcon,
  InformationCircleIcon,
  EllipsisHorizontalIcon,
} from "@heroicons/react/24/outline";
import {
  useEventManager,
  useEventOrderManager,
} from "../../../../../../../services/Services";
import { DetailLiteView, useUIXTheme } from "../../../../../../../components/UIX";
import { EVENT_TYPE_ONSITE } from "../../../../../../../constants/Event";

// EventOrder status mappings (matching backend EventOrder)
const EVENT_ORDER_STATUS_OPTIONS = {
  1: { label: "Active", themeKey: "text-success" },
  2: { label: "Archived", themeKey: "text-muted" },
};

function AdminInSchoolDetailOrderListPage() {
  const { eventId } = useParams();
  const navigate = useNavigate();
  const eventManager = useEventManager();
  const eventOrderManager = useEventOrderManager();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [isRefreshing, setRefreshing] = useState(false);
  const [event, setEvent] = useState(null);
  const [eventOrderList, setEventOrderList] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [lastFetchTime, setLastFetchTime] = useState(null);

  // Pagination state
  const [pageSize] = useState(50);
  const [sortByValue] = useState("created_at,DESC");
  const [status] = useState(0);

  // Use refs to track the latest filter values
  const filtersRef = useRef({
    sortByValue,
    status,
    pageSize,
  });

  // Update refs when filters change
  useEffect(() => {
    filtersRef.current = {
      sortByValue,
      status,
      pageSize,
    };
  }, [sortByValue, status, pageSize]);

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

  // Fetch event order list
  const fetchEventOrderList = useCallback(async () => {
    const currentFilters = filtersRef.current;

    console.log("🔄 fetchEventOrderList called with filters:", currentFilters);

    setFetching(true);
    setErrors({});

    eventOrderManager.clearEventOrdersCache();

    try {
      // Build filters map
      const filtersMap = new Map();
      filtersMap.set("page_size", currentFilters.pageSize.toString());
      filtersMap.set("event_id", eventId);

      const sortArray = currentFilters.sortByValue.split(",");
      filtersMap.set("sort_field", sortArray[0]);
      filtersMap.set("sort_order", sortArray[1]);

      if (currentFilters.status !== 0) {
        filtersMap.set("status", currentFilters.status.toString());
      }

      console.log("🌐 Making API call with filters:", Array.from(filtersMap.entries()));

      const data = await eventOrderManager.getEventOrdersWithFiltersMap(
        filtersMap,
        onUnauthorized,
        true,
      );

      console.log("✅ API response received:", {
        resultsCount: data.results?.length,
        totalCount: data.count,
      });

      setEventOrderList(data.results || []);
      setTotalCount(data.count || 0);
      setLastFetchTime(new Date());
    } catch (error) {
      console.error("❌ Failed to fetch event order list:", error);
      setErrors(error);
    } finally {
      setFetching(false);
      setRefreshing(false);
    }
  }, [eventId, eventOrderManager, onUnauthorized]);

  // Fetch event details
  const fetchEvent = useCallback(async () => {
    if (!eventId) return;

    setFetching(true);
    setErrors({});

    try {
      const eventData = await eventManager.getEventDetail(eventId, onUnauthorized);

      // Verify this is an in-school (onsite) event
      if (eventData.type !== EVENT_TYPE_ONSITE) {
        setErrors({ message: "This event is not an in-school event" });
        return;
      }

      setEvent(eventData);
    } catch (err) {
      setErrors({ message: "Failed to load in-school event details. Please try again." });
    } finally {
      setFetching(false);
    }
  }, [eventId, eventManager, onUnauthorized]);

  // Initial load
  useEffect(() => {
    window.scrollTo(0, 0);
    fetchEvent();
  }, [fetchEvent]);

  // Fetch event orders after event is loaded
  useEffect(() => {
    if (event?.id) {
      fetchEventOrderList();
    }
  }, [event?.id, fetchEventOrderList]);

  // Refresh handler
  const handleRefresh = useCallback(() => {
    setRefreshing(true);
    fetchEventOrderList();
  }, [fetchEventOrderList]);

  // Configure breadcrumb items
  const breadcrumbItems = useMemo(() => [
    {
      label: 'Dashboard',
      to: '/admin/dashboard',
      icon: HomeIcon,
      hideOnMobile: false,
      mobileLabel: 'Dash'
    },
    {
      label: 'In-School Events',
      to: '/admin/events/in-schools',
      icon: AcademicCapIcon
    },
    {
      label: 'Event Orders',
      icon: ShoppingCartIcon,
      isActive: true
    }
  ], []);

  const headerConfig = useMemo(() => ({
    title: 'In-School - Event Orders',
    icon: AcademicCapIcon,
    loadingText: 'Loading in-school event orders...',
    notFoundTitle: 'In-School Event Not Found',
    notFoundMessage: "The in-school event you're looking for doesn't exist or you don't have permission to view it.",
    notFoundAction: {
      label: 'Back to In-School Events',
      icon: ChevronLeftIcon,
      onClick: () => navigate('/admin/events/in-schools')
    }
  }), [navigate]);

  const actionButtons = useMemo(() => [
    {
      variant: "outline",
      onClick: () => navigate('/admin/events/in-schools'),
      icon: ChevronLeftIcon,
      label: "Back"
    }
  ], [navigate]);

  const tabs = useMemo(() => {
    if (!eventId) return [];

    return [
      {
        label: "Summary",
        to: `/admin/events/in-school/${eventId}`
      },
      {
        label: "Details",
        to: `/admin/events/in-school/${eventId}/full`
      },
      {
        label: "Orders",
        isActive: true
      },
      {
        label: "Comments",
        to: `/admin/events/in-school/${eventId}/comments`
      },
      {
        label: "Attachments",
        to: `/admin/events/in-school/${eventId}/attachments`
      },
      {
        label: "More",
        to: `/admin/events/in-school/${eventId}/more`,
        icon: EllipsisHorizontalIcon
      }
    ];
  }, [eventId]);

  // Create field sections for the event orders list
  const fieldSections = useMemo(() => {
    const sections = [
      {
        column: 'primary',
        className: 'mb-6',
        component: (
          <div>
            <div className="flex justify-between items-center mb-4">
              <h2 className={`text-xl sm:text-2xl font-bold ${getThemeClasses('text-primary')}`}>
                Event Orders for {event?.eventName || "Loading..."}
              </h2>
              <button
                onClick={handleRefresh}
                disabled={isRefreshing || isFetching}
                className={`inline-flex items-center px-4 py-2 border rounded-lg text-sm font-medium transition-colors ${
                  isRefreshing || isFetching
                    ? 'opacity-50 cursor-not-allowed'
                    : getThemeClasses('hover-bg-muted')
                } ${getThemeClasses('border-border')} ${getThemeClasses('text-secondary')}`}
              >
                <ArrowPathIcon
                  className={`w-4 h-4 mr-2 ${isRefreshing || isFetching ? "animate-spin" : ""}`}
                />
                {isRefreshing ? "Refreshing..." : "Refresh"}
              </button>
            </div>

            {lastFetchTime && (
              <div className={`text-sm mb-4 flex items-center ${getThemeClasses('text-muted')}`}>
                <ClockIcon className="w-4 h-4 mr-1" />
                Last updated {Math.floor((new Date() - lastFetchTime) / 1000)} seconds ago
              </div>
            )}

            <div className={`mb-4 ${getThemeClasses('text-muted')}`}>
              Showing{" "}
              <strong className={getThemeClasses('text-primary')}>
                {eventOrderList.length}
              </strong>{" "}
              event orders
              {totalCount > 0 && ` (Total: ${totalCount})`}
            </div>

            {/* Event Orders List */}
            {isFetching ? (
              <div className="flex items-center justify-center py-12">
                <div className="text-center">
                  <div className={`animate-spin rounded-full h-10 w-10 border-b-2 mx-auto ${getThemeClasses('border-primary')}`}></div>
                  <p className={`mt-4 ${getThemeClasses('text-muted')}`}>
                    Loading event orders...
                  </p>
                </div>
              </div>
            ) : eventOrderList && eventOrderList.length > 0 ? (
              <div className="space-y-3">
                {eventOrderList.map((eventOrder, index) => (
                  <div
                    key={eventOrder.id || index}
                    className={`rounded-lg border p-4 ${getThemeClasses('bg-card')} ${getThemeClasses('border-border')}`}
                  >
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                      <div>
                        <strong className={getThemeClasses('text-secondary')}>Order #:</strong>
                        <div className={`font-mono text-sm ${getThemeClasses('text-primary')}`}>
                          #{eventOrder.publicId}
                        </div>
                      </div>
                      <div>
                        <strong className={getThemeClasses('text-secondary')}>Customer:</strong>
                        <div className={`font-medium ${getThemeClasses('text-primary')}`}>
                          {eventOrder.customerName || "N/A"}
                        </div>
                      </div>
                      <div>
                        <strong className={getThemeClasses('text-secondary')}>Status:</strong>
                        <div
                          className={
                            getThemeClasses(EVENT_ORDER_STATUS_OPTIONS[eventOrder.status]?.themeKey || "text-muted")
                          }
                        >
                          {EVENT_ORDER_STATUS_OPTIONS[eventOrder.status]?.label || "Unknown"}
                        </div>
                      </div>
                      <div className="flex justify-end items-center">
                        <Link
                          to={`/admin/event-order/${eventOrder.id}`}
                          className={`inline-flex items-center font-medium ${getThemeClasses("link-primary")}`}
                        >
                          View Order
                          <ArrowRightIcon className="w-3 h-3 ml-1" />
                        </Link>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className={`text-center py-16 rounded-lg ${getThemeClasses('bg-card')}`}>
                <ShoppingCartIcon className={`w-12 h-12 mx-auto mb-4 ${getThemeClasses('text-muted')}`} />
                <h3 className={`text-lg font-medium mb-2 ${getThemeClasses('text-primary')}`}>
                  No Event Orders Found
                </h3>
                <p className={getThemeClasses('text-muted')}>
                  This in-school event does not have any orders yet.
                </p>
              </div>
            )}
          </div>
        )
      }
    ];

    return sections;
  }, [
    event,
    eventOrderList,
    totalCount,
    lastFetchTime,
    isFetching,
    isRefreshing,
    handleRefresh,
    getThemeClasses
  ]);

  const alerts = useMemo(() => ({
    archived: {
      message: 'This in-school event is archived',
      icon: ArchiveBoxIcon
    }
  }), []);

  return (
    <DetailLiteView
      entityData={event}
      breadcrumbItems={breadcrumbItems}
      headerConfig={headerConfig}
      fieldSections={fieldSections}
      actionButtons={actionButtons}
      tabs={tabs}
      alerts={alerts}
      onUnauthorized={onUnauthorized}
      isLoading={isFetching && !event}
      error={errors?.message}
      onErrorClose={() => setErrors({})}
    />
  );
}

export default AdminInSchoolDetailOrderListPage;
