// File Path: monorepo/web/frontend/src/pages/Admin/EventOrder/Add/Step5Page.jsx

import React, { useState, useEffect, useRef } from "react";
import { Link, useNavigate } from "react-router";
import {
  useEventOrderWizardStorage,
  useEventOrderManager,
  useAttachmentManager,
  useEventManager,
} from "../../../../services/Services";
import {
  Button,
  Card,
  Alert,
  Spinner,
  Badge,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  ChevronRightIcon,
  ChartBarIcon,
  TicketIcon,
  UserIcon,
  CalendarIcon,
  MapPinIcon,
  ClockIcon,
  EnvelopeIcon,
  PhoneIcon,
  CheckCircleIcon,
  ArrowLeftIcon,
  ExclamationTriangleIcon,
  InformationCircleIcon,
  UserGroupIcon,
  PaperClipIcon,
  DocumentIcon,
  LinkIcon,
  BuildingOfficeIcon,
  TagIcon,
  AcademicCapIcon,
  InformationCircleIcon as InfoIcon,
} from "@heroicons/react/24/outline";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";
import CertificationDisplay from "../../../../components/business/displays/CertificationDisplay";
import SpecializationDisplay from "../../../../components/business/displays/SpecializationDisplay";
import EventCategoryDisplay from "../../../../components/business/displays/EventCategoryDisplay";
import { getEventOrderSectorLabel } from "../../../../constants/EventOrder";
import {
  EVENT_TYPE_CONFERENCE,
  EVENT_TYPE_ONSITE,
  EVENT_TYPE_OFFSITE,
  EVENT_TYPE_VIRTUAL,
  EVENT_STATUS_ACTIVE,
  EVENT_STATUS_ARCHIVED,
} from "../../../../constants/Event";

function AdminEventOrderAddStep5Page() {
  const navigate = useNavigate();
  const wizardStorage = useEventOrderWizardStorage();
  const eventOrderManager = useEventOrderManager();
  const attachmentManager = useAttachmentManager();
  const eventManager = useEventManager();
  const { getThemeClasses } = useUIXTheme();

  // Refs for scroll control
  const pageTopRef = useRef(null);
  const errorRef = useRef(null);

  // State management
  const [customer, setCustomer] = useState(null);
  const [event, setEvent] = useState(null);
  const [eventDetails, setEventDetails] = useState(null);
  const [orderDetails, setOrderDetails] = useState(null);
  const [attachments, setAttachments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [loadingEventDetails, setLoadingEventDetails] = useState(false);
  const [error, setError] = useState(null);
  const [submitting, setSubmitting] = useState(false);

  // Handle unauthorized access
  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };

  // Helper function to get event type label
  const getEventTypeLabel = (typeValue) => {
    switch (parseInt(typeValue)) {
      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 "Unknown";
    }
  };

  // Helper function to get event status label
  const getEventStatusLabel = (statusValue) => {
    switch (parseInt(statusValue)) {
      case EVENT_STATUS_ACTIVE:
        return "Active";
      case EVENT_STATUS_ARCHIVED:
        return "Archived";
      default:
        return "Unknown";
    }
  };

  // Get temporary attachment IDs from wizard storage
  const getTemporaryAttachmentIds = () => {
    const attachmentIds =
      wizardStorage.getWizardStep("temporaryAttachmentIds") || [];
    return Array.isArray(attachmentIds) ? attachmentIds : [];
  };

  // Load attachments for display
  const loadAttachments = async () => {
    try {
      const temporaryAttachmentIds = getTemporaryAttachmentIds();

      if (temporaryAttachmentIds.length === 0) {
        setAttachments([]);
        return;
      }

      // Get all temporary attachments and filter by our IDs
      const attachmentsData = await attachmentManager.getAttachments(
        {
          ownershipType: "temporary",
          sortBy: "created_at",
          sortOrder: "DESC",
          limit: 1000,
        },
        onUnauthorized,
        true,
      );

      // Filter to only show attachments with temporaryIds that match our stored IDs
      const filteredAttachments = (attachmentsData.results || []).filter(
        (attachment) => temporaryAttachmentIds.includes(attachment.temporaryId),
      );

      setAttachments(filteredAttachments);
    } catch (error) {
      if (process.env.NODE_ENV === "development") {
        console.error("Step5Page: Failed to load attachments", error);
      }
    }
  };

  // Load detailed event information
  const loadEventDetails = async (eventId) => {
    try {
      setLoadingEventDetails(true);

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

      setEventDetails(eventData);
    } catch (error) {
      if (process.env.NODE_ENV === "development") {
        console.error("Step5Page: Failed to load event details", error);
      }
    } finally {
      setLoadingEventDetails(false);
    }
  };

  // Scroll to top when error occurs
  useEffect(() => {
    if (error && errorRef.current) {
      errorRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  }, [error]);

  // Load wizard data on mount
  useEffect(() => {
    const customerData = wizardStorage.getCustomer();
    const eventData = wizardStorage.getEvent();
    const orderDetailsData = wizardStorage.getOrderDetails();

    // Check if we have required data
    if (!customerData) {
      setError("Customer information is missing. Please start from step 1.");
      return;
    }

    if (!eventData) {
      setError(
        "Event information is missing. Please select an event in step 2.",
      );
      return;
    }

    if (
      !orderDetailsData ||
      !orderDetailsData.eventAttendeeCapacity ||
      !orderDetailsData.sector ||
      !orderDetailsData.eventCategoryId ||
      !orderDetailsData.specializationIds ||
      !orderDetailsData.certificationIds
    ) {
      setError(
        "Order requirements are missing. Please complete all requirements in step 3.",
      );
      return;
    }

    setCustomer(customerData);
    setEvent(eventData);
    setOrderDetails(orderDetailsData);

    // Load detailed event information if we have an event
    if (eventData && eventData.id) {
      loadEventDetails(eventData.id);
    }

    // Load attachments
    loadAttachments();
  }, [wizardStorage]);

  // Handle order submission
  const handleSubmitOrder = async () => {
    if (!customer || !event || !orderDetails) {
      setError("Missing required information. Please complete all steps.");
      return;
    }

    setSubmitting(true);
    setError(null);

    try {
      // Get temporary attachment IDs
      const temporaryAttachmentIds = getTemporaryAttachmentIds();

      // Prepare event order data - only send fields that backend API expects
      const eventOrderData = {
        eventId: event.id,
        customerId: customer.id,
        additionalOrderNotes: orderDetails.additionalOrderNotes || "",
        temporaryAttachmentIds: temporaryAttachmentIds,
        estimated_number_of_attendees: orderDetails.eventAttendeeCapacity,
      };

      // Create the event order
      const result = await eventOrderManager.createEventOrder(
        eventOrderData,
        onUnauthorized,
      );

      // Clear wizard data
      wizardStorage.clearWizardData();

      // Navigate to event orders list
      navigate("/admin/event-orders");
    } catch (err) {
      if (process.env.NODE_ENV === "development") {
        console.error("Failed to create event order:", err);
      }

      // Helper function to format field name for display
      const formatFieldName = (fieldName) => {
        return fieldName
          .replace(/_/g, " ")
          .replace(/([A-Z])/g, " $1")
          .toLowerCase()
          .replace(/^./, (str) => str.toUpperCase());
      };

      // Handle different error types - including backend validation errors
      if (typeof err === "object" && err !== null) {
        // Field-specific validation errors
        if (err.eventId) {
          setError(
            `Event Selection Error\n\nThe selected event is invalid or missing.\n\nPlease go back to Step 1 and select a valid event.`,
          );
        } else if (err.customerId) {
          setError(
            `Customer Selection Error\n\nThe selected customer is invalid or missing.\n\nPlease go back to Step 2 and select a valid customer.`,
          );
        } else if (err.estimatedNumberOfAttendees) {
          setError(
            `Attendance Error\n\nThe number of attendees is invalid: ${err.estimatedNumberOfAttendees}\n\nPlease verify the attendance count and try again.`,
          );
        }
        // Customer-related validation errors from task creation
        else if (err.customerEmail) {
          setError(
            `Missing Customer Email\n\nThe selected customer does not have an email address on file, which is required to create event orders.\n\nPlease go back to Step 2 and either:\n• Select a different customer who has an email address, or\n• Update the customer's profile to add their email address\n\nThen try creating the order again.`,
          );
        } else if (err.customerPhone) {
          setError(
            `Missing Customer Phone Number\n\nThe selected customer does not have a phone number on file, which is required to create event orders.\n\nPlease go back to Step 2 and either:\n• Select a different customer who has a phone number, or\n• Update the customer's profile to add their phone number\n\nThen try creating the order again.`,
          );
        } else if (err.customerName) {
          setError(
            `Missing Customer Name\n\nThe selected customer is missing required name information.\n\nPlease go back to Step 2 and select a valid customer with complete profile information.`,
          );
        } else if (
          err.customerOrganizationName ||
          err.customerOrganizationShortName
        ) {
          setError(
            `Missing Organization Information\n\nThe selected customer's organization is missing required information (${err.customerOrganizationName ? "organization name" : "organization short name"}).\n\nPlease ensure the selected customer belongs to an organization with complete information, or contact your system administrator to update the organization details.`,
          );
        } else if (err.customerDivisionName || err.customerDivisionShortName) {
          setError(
            `Missing Division Information\n\nThe selected customer's division is missing required information (${err.customerDivisionName ? "division name" : "division short name"}).\n\nPlease ensure the selected customer belongs to a division with complete information, or contact your system administrator to update the division details.`,
          );
        }
        // Event-related validation errors
        else if (err.eventName || err.eventDescription) {
          setError(
            `Invalid Event Information\n\nThe selected event is missing required information (${err.eventName ? "event name" : "event description"}).\n\nPlease go back to Step 1 and select a different event, or contact your system administrator to update the event details.`,
          );
        } else if (err.eventCategoryName) {
          setError(
            `Missing Event Category\n\nThe event category information is missing or invalid.\n\nPlease go back to Step 3 and ensure an event category is selected.`,
          );
        }
        // General error handling
        else if (err.general) {
          setError(err.general);
        } else if (err.message) {
          setError(
            `Error Creating Event Order\n\n${err.message}\n\nPlease review the information above and try again.`,
          );
        } else {
          // Display all error fields if present
          const errorFields = Object.keys(err);
          if (errorFields.length > 0) {
            const errorMessages = errorFields
              .map((field) => `• ${formatFieldName(field)}: ${err[field]}`)
              .join("\n");
            setError(
              `Validation Errors\n\nThe following fields have errors:\n\n${errorMessages}\n\nPlease correct these errors and try again.`,
            );
          } else {
            setError(
              "Unexpected Error\n\nAn unexpected error occurred while creating the event order.\n\nPlease try again. If the problem persists, contact support.",
            );
          }
        }
      } else if (err && err.message) {
        setError(
          `Error Creating Event Order\n\n${err.message}\n\nPlease review the information above and try again.`,
        );
      } else {
        setError(
          "Unexpected Error\n\nAn unexpected error occurred while creating the event order.\n\nPlease try again. If the problem persists, contact support.",
        );
      }
    } finally {
      setSubmitting(false);
    }
  };

  // Handle going back to additional details
  const handleBackToAdditionalDetails = () => {
    navigate("/admin/event-orders/add/step-4");
  };

  // Handle starting over
  const handleStartOver = () => {
    wizardStorage.clearWizardData();
    navigate("/admin/event-orders/add/step-1-search");
  };

  // Show loading state while checking wizard data
  if (!customer && !event && !error) {
    return (
      <div className={`min-h-screen ${getThemeClasses("page-bg")}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="flex flex-col items-center justify-center py-12">
            <Spinner size="lg" />
            <p className={`mt-4 ${getThemeClasses("text-secondary")}`}>
              Loading order summary...
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
      className="min-h-screen ${getThemeClasses('bg-muted')}"
      ref={pageTopRef}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Breadcrumb */}
        <nav className="flex mb-8" aria-label="Breadcrumb">
          <ol className="inline-flex items-center space-x-1 md:space-x-3">
            <li className="inline-flex items-center">
              <Link
                to="/admin/dashboard"
                className="inline-flex items-center text-sm font-medium ${getThemeClasses('text-secondary')} hover:text-blue-600"
              >
                <ChartBarIcon className="w-4 h-4 mr-2" />
                Dashboard
              </Link>
            </li>
            <li>
              <div className="flex items-center">
                <ChevronRightIcon className="w-5 h-5 ${getThemeClasses('text-muted')}" />
                <Link
                  to="/admin/event-orders"
                  className="ml-1 text-sm font-medium ${getThemeClasses('text-secondary')} hover:text-blue-600 md:ml-2"
                >
                  Event Orders
                </Link>
              </div>
            </li>
            <li aria-current="page">
              <div className="flex items-center">
                <ChevronRightIcon className="w-5 h-5 ${getThemeClasses('text-muted')}" />
                <span className="ml-1 text-sm font-medium ${getThemeClasses('text-primary')} md:ml-2">
                  Create New Order
                </span>
              </div>
            </li>
          </ol>
        </nav>

        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold ${getThemeClasses('text-primary')} flex items-center">
            <TicketIcon className="w-8 h-8 mr-3 text-blue-600" />
            Create Event Order - Step 5: Review & Confirm
          </h1>
          <p className="mt-2 ${getThemeClasses('text-secondary')}">
            Review your selections below and confirm to create the event order.
          </p>
        </div>

        {/* Progress Steps */}
        <div className="mb-8">
          <div className="flex items-center">
            <div className="flex items-center">
              <div className="flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white text-sm font-bold">
                <CheckCircleIcon className="w-5 h-5" />
              </div>
              <span className="ml-2 text-sm font-medium ${getThemeClasses('text-primary')}">
                Find Customer
              </span>
            </div>
            <ChevronRightIcon className="w-5 h-5 ${getThemeClasses('text-muted')} mx-4" />
            <div className="flex items-center">
              <div className="flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white text-sm font-bold">
                <CheckCircleIcon className="w-5 h-5" />
              </div>
              <span className="ml-2 text-sm font-medium ${getThemeClasses('text-primary')}">
                Select Event
              </span>
            </div>
            <ChevronRightIcon className="w-5 h-5 ${getThemeClasses('text-muted')} mx-4" />
            <div className="flex items-center">
              <div className="flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white text-sm font-bold">
                <CheckCircleIcon className="w-5 h-5" />
              </div>
              <span className="ml-2 text-sm font-medium ${getThemeClasses('text-primary')}">
                Order Requirements
              </span>
            </div>
            <ChevronRightIcon className="w-5 h-5 ${getThemeClasses('text-muted')} mx-4" />
            <div className="flex items-center">
              <div className="flex items-center justify-center w-8 h-8 bg-green-600 rounded-full text-white text-sm font-bold">
                <CheckCircleIcon className="w-5 h-5" />
              </div>
              <span className="ml-2 text-sm font-medium ${getThemeClasses('text-primary')}">
                Additional Details
              </span>
            </div>
            <ChevronRightIcon className="w-5 h-5 ${getThemeClasses('text-muted')} mx-4" />
            <div className="flex items-center">
              <div className="flex items-center justify-center w-8 h-8 bg-blue-600 rounded-full text-white text-sm font-bold">
                5
              </div>
              <span className="ml-2 text-sm font-medium ${getThemeClasses('text-primary')}">
                Review & Confirm
              </span>
            </div>
          </div>
        </div>

        {/* Error Messages */}
        {error && (
          <div ref={errorRef} className="mb-6">
            <Alert type="error" dismissible onDismiss={() => setError(null)}>
              <div className="flex">
                <div className="flex-shrink-0">
                  <ExclamationTriangleIcon className="h-5 w-5 text-red-400" />
                </div>
                <div className="ml-3 flex-1">
                  <h3 className="text-sm font-medium text-red-800">
                    Unable to Create Event Order
                  </h3>
                  <div className="mt-2 text-sm text-red-700">
                    <p className="whitespace-pre-wrap">{error}</p>
                  </div>
                  {error.includes("Step 2") && (
                    <div className="mt-4">
                      <Link to="/admin/event-orders/add/step-2-search">
                        <Button variant="secondary" size="sm">
                          <ArrowLeftIcon className="w-4 h-4 mr-1" />
                          Go to Step 2 - Customer Selection
                        </Button>
                      </Link>
                    </div>
                  )}
                  {error.includes("Step 1") && (
                    <div className="mt-4">
                      <Link to="/admin/event-orders/add/step-1-search">
                        <Button variant="secondary" size="sm">
                          <ArrowLeftIcon className="w-4 h-4 mr-1" />
                          Go to Step 1 - Event Selection
                        </Button>
                      </Link>
                    </div>
                  )}
                  {error.includes("Step 3") && (
                    <div className="mt-4">
                      <Link to="/admin/event-orders/add/step-3">
                        <Button variant="secondary" size="sm">
                          <ArrowLeftIcon className="w-4 h-4 mr-1" />
                          Go to Step 3 - Requirements
                        </Button>
                      </Link>
                    </div>
                  )}
                </div>
              </div>
            </Alert>
          </div>
        )}

        {/* Order Summary */}
        {customer && event && orderDetails && (
          <div className="space-y-6">
            {/* Customer Summary Card */}
            <Card>
              <div className="p-6">
                <div className="flex items-center mb-4">
                  <UserIcon className="w-6 h-6 text-blue-600 mr-2" />
                  <h2 className="text-xl font-semibold ${getThemeClasses('text-primary')}">
                    Selected Customer
                  </h2>
                </div>

                <div className="${getThemeClasses('bg-muted')} rounded-lg p-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <h3 className="font-medium ${getThemeClasses('text-primary')} mb-2">
                        {customer.name ||
                          `${customer.firstName} ${customer.lastName}`}
                      </h3>
                      {customer.organization && (
                        <p className="text-sm ${getThemeClasses('text-secondary')} mb-1">
                          {customer.organization}
                        </p>
                      )}
                      <div className="space-y-1">
                        {customer.email && (
                          <div className="flex items-center text-sm ${getThemeClasses('text-secondary')}">
                            <EnvelopeIcon className="w-4 h-4 mr-2" />
                            {customer.email}
                          </div>
                        )}
                        {customer.phone && (
                          <div className="flex items-center text-sm ${getThemeClasses('text-secondary')}">
                            <PhoneIcon className="w-4 h-4 mr-2" />
                            {customer.phone}
                          </div>
                        )}
                      </div>
                    </div>
                    <div>
                      {(customer.city || customer.region) && (
                        <div className="flex items-center text-sm ${getThemeClasses('text-secondary')} mb-2">
                          <MapPinIcon className="w-4 h-4 mr-2" />
                          {[customer.city, customer.region]
                            .filter(Boolean)
                            .join(", ")}
                        </div>
                      )}
                      <Badge
                        variant={customer.type === 2 ? "primary" : "default"}
                        size="sm"
                      >
                        {customer.type === 2 ? "Business" : "Individual"}
                      </Badge>
                    </div>
                  </div>
                </div>
              </div>
            </Card>

            {/* Event Summary Card */}
            <Card>
              <div className="p-6">
                <div className="flex items-center mb-4">
                  <CalendarIcon className="w-6 h-6 text-blue-600 mr-2" />
                  <h2 className="text-xl font-semibold ${getThemeClasses('text-primary')}">
                    Selected Event
                  </h2>
                  <div className="ml-auto">
                    <Link to="/admin/event-orders/add/step-2-search">
                      <Button variant="secondary" size="sm">
                        Change Event
                      </Button>
                    </Link>
                  </div>
                </div>

                {loadingEventDetails ? (
                  <div className="text-center py-8">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
                    <p className="mt-2 ${getThemeClasses('text-secondary')}">
                      Loading detailed event information...
                    </p>
                  </div>
                ) : (
                  <div className="${getThemeClasses('bg-muted')} rounded-lg p-4">
                    {/* Event Title */}
                    <div className="mb-4">
                      <h3 className="text-lg font-semibold ${getThemeClasses('text-primary')} mb-2">
                        {eventDetails?.eventName ||
                          event.eventName ||
                          eventDetails?.name ||
                          event.name}
                      </h3>
                      {(eventDetails?.description || event.description) && (
                        <p className="text-sm ${getThemeClasses('text-secondary')}">
                          {eventDetails?.description || event.description}
                        </p>
                      )}
                    </div>

                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                      {/* Left Column */}
                      <div className="space-y-4">
                        {/* Event Type */}
                        {(eventDetails?.type || event.type) && (
                          <div>
                            <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-1">
                              <TagIcon className="w-4 h-4 mr-2" />
                              Event Type
                            </div>
                            <Badge variant="secondary" size="sm">
                              {getEventTypeLabel(
                                eventDetails?.type || event.type,
                              )}
                            </Badge>
                          </div>
                        )}

                        {/* Start Date and Time */}
                        {(eventDetails?.startDateTime ||
                          event.startDateTime) && (
                          <div>
                            <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-1">
                              <CalendarIcon className="w-4 h-4 mr-2" />
                              Event Start Date & Time
                            </div>
                            <p className="text-sm font-medium ${getThemeClasses('text-primary')}">
                              {formatDateForDisplay(
                                eventDetails?.startDateTime ||
                                  event.startDateTime,
                              )}
                            </p>
                          </div>
                        )}

                        {/* End Date and Time */}
                        {(eventDetails?.endDateTime ||
                          event.endDateTime ||
                          eventDetails?.finishDateTime ||
                          event.finishDateTime) && (
                          <div>
                            <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-1">
                              <CalendarIcon className="w-4 h-4 mr-2" />
                              Event End Date & Time
                            </div>
                            <p className="text-sm font-medium ${getThemeClasses('text-primary')}">
                              {formatDateForDisplay(
                                eventDetails?.endDateTime ||
                                  event.endDateTime ||
                                  eventDetails?.finishDateTime ||
                                  event.finishDateTime,
                              )}
                            </p>
                          </div>
                        )}

                        {/* Location */}
                        {(eventDetails?.location || event.location) && (
                          <div>
                            <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-1">
                              <MapPinIcon className="w-4 h-4 mr-2" />
                              Location
                            </div>
                            <p className="text-sm font-medium ${getThemeClasses('text-primary')}">
                              {eventDetails?.location || event.location}
                            </p>
                          </div>
                        )}

                        {/* URL */}
                        {(eventDetails?.listingUrl || eventDetails?.url) && (
                          <div>
                            <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-1">
                              <LinkIcon className="w-4 h-4 mr-2" />
                              Event URL
                            </div>
                            <a
                              href={
                                eventDetails?.listingUrl || eventDetails?.url
                              }
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-sm text-blue-600 hover:text-blue-800 hover:underline break-all"
                            >
                              {eventDetails?.listingUrl || eventDetails?.url}
                            </a>
                          </div>
                        )}
                      </div>

                      {/* Right Column */}
                      <div className="space-y-4">
                        {/* Partner/Organization */}
                        {(eventDetails?.partners ||
                          eventDetails?.organizationName ||
                          eventDetails?.organization?.name) && (
                          <div>
                            <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-1">
                              <BuildingOfficeIcon className="w-4 h-4 mr-2" />
                              Partner
                            </div>
                            <p className="text-sm font-medium ${getThemeClasses('text-primary')}">
                              {eventDetails?.partners ||
                                eventDetails?.organizationName ||
                                eventDetails?.organization?.name}
                            </p>
                          </div>
                        )}

                        {/* Status */}
                        {(eventDetails?.status || event.status) && (
                          <div>
                            <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-1">
                              <CheckCircleIcon className="w-4 h-4 mr-2" />
                              Status
                            </div>
                            <Badge
                              variant={
                                (eventDetails?.status || event.status) ===
                                EVENT_STATUS_ACTIVE
                                  ? "success"
                                  : "default"
                              }
                              size="sm"
                            >
                              {getEventStatusLabel(
                                eventDetails?.status || event.status,
                              )}
                            </Badge>
                          </div>
                        )}

                        {/* Capacity Information */}
                        {(eventDetails?.attendeeCapacity ||
                          event.attendeeCapacity) && (
                          <div>
                            <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-1">
                              <UserGroupIcon className="w-4 h-4 mr-2" />
                              Capacity Information
                            </div>
                            <div className="space-y-1 text-sm">
                              <p>
                                <strong>Total Capacity:</strong>{" "}
                                {eventDetails?.attendeeCapacity ||
                                  event.attendeeCapacity}{" "}
                                attendees
                              </p>
                              {(eventDetails?.attendeeCount !== undefined ||
                                event.attendeeCount !== undefined) && (
                                <>
                                  <p>
                                    <strong>Current Registered:</strong>{" "}
                                    {eventDetails?.attendeeCount ||
                                      event.attendeeCount ||
                                      0}{" "}
                                    attendees
                                  </p>
                                  <p>
                                    <strong>Available Slots:</strong>{" "}
                                    {(eventDetails?.attendeeCapacity ||
                                      event.attendeeCapacity) -
                                      (eventDetails?.attendeeCount ||
                                        event.attendeeCount ||
                                        0)}{" "}
                                    slots
                                  </p>
                                </>
                              )}
                            </div>
                          </div>
                        )}

                        {/* Skill Sets */}
                        {eventDetails?.skillSets &&
                          eventDetails.skillSets.length > 0 && (
                            <div>
                              <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-2">
                                <AcademicCapIcon className="w-4 h-4 mr-2" />
                                Required Skill Sets
                              </div>
                              <div className="flex flex-wrap gap-2">
                                {eventDetails.skillSets.map(
                                  (skillSet, index) => (
                                    <Badge
                                      key={index}
                                      variant="outline"
                                      size="sm"
                                    >
                                      {typeof skillSet === "string"
                                        ? skillSet
                                        : skillSet?.category ||
                                          skillSet?.subCategory ||
                                          skillSet?.description ||
                                          `Skill Set ${index + 1}`}
                                    </Badge>
                                  ),
                                )}
                              </div>
                            </div>
                          )}
                      </div>
                    </div>

                    {/* Additional Information - separate from main description */}
                    {(eventDetails?.additionalInformation ||
                      eventDetails?.notes) && (
                      <div className="mt-4 pt-4 border-t ${getThemeClasses('border-border')}">
                        <div className="flex items-center text-sm ${getThemeClasses('text-muted')} mb-2">
                          <InfoIcon className="w-4 h-4 mr-2" />
                          Additional Information
                        </div>
                        <div className="bg-white rounded-lg p-3 border">
                          <p className="text-sm ${getThemeClasses('text-secondary')} whitespace-pre-wrap">
                            {eventDetails?.additionalInformation ||
                              eventDetails?.notes}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </Card>

            {/* Attendance Summary Card */}
            <Card>
              <div className="p-6">
                <div className="flex items-center mb-4">
                  <UserGroupIcon className="w-6 h-6 text-blue-600 mr-2" />
                  <h2 className="text-xl font-semibold ${getThemeClasses('text-primary')}">
                    Selected Attendance
                  </h2>
                </div>

                <div className="${getThemeClasses('bg-muted')} rounded-lg p-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <h3 className="font-medium ${getThemeClasses('text-primary')} mb-2">
                        Number of Attendees for This Order
                      </h3>
                      <div className="flex items-center">
                        <Badge variant="primary" size="lg" className="mr-2">
                          {orderDetails.eventAttendeeCapacity}{" "}
                          {orderDetails.eventAttendeeCapacity === 1
                            ? "attendee"
                            : "attendees"}
                        </Badge>
                      </div>
                    </div>
                    <div>
                      {event.attendeeCapacity && (
                        <div className="space-y-1">
                          <p className="text-sm ${getThemeClasses('text-secondary')}">
                            <strong>Total Event Capacity:</strong>{" "}
                            {event.attendeeCapacity} attendees
                          </p>
                          {event.attendeeCount !== undefined && (
                            <>
                              <p className="text-sm ${getThemeClasses('text-secondary')}">
                                <strong>Current Registrations:</strong>{" "}
                                {event.attendeeCount} attendees
                              </p>
                              <p className="text-sm ${getThemeClasses('text-secondary')}">
                                <strong>Available Before This Order:</strong>{" "}
                                {event.attendeeCapacity - event.attendeeCount}{" "}
                                slots
                              </p>
                              <p className="text-sm font-medium ${getThemeClasses('text-secondary')}">
                                <strong>Remaining After This Order:</strong>{" "}
                                {event.attendeeCapacity -
                                  event.attendeeCount -
                                  orderDetails.eventAttendeeCapacity}{" "}
                                slots
                              </p>
                            </>
                          )}
                          {event.attendeeCount === undefined && (
                            <p className="text-sm ${getThemeClasses('text-secondary')}">
                              <strong>Remaining After This Order:</strong>{" "}
                              {event.attendeeCapacity -
                                orderDetails.eventAttendeeCapacity}{" "}
                              attendees
                            </p>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </Card>

            {/* Order Requirements Summary Card */}
            <Card>
              <div className="p-6">
                <div className="flex items-center mb-4">
                  <CheckCircleIcon className="w-6 h-6 text-blue-600 mr-2" />
                  <h2 className="text-xl font-semibold ${getThemeClasses('text-primary')}">
                    Order Requirements
                  </h2>
                </div>

                <div className="${getThemeClasses('bg-muted')} rounded-lg p-4">
                  <div className="space-y-6">
                    {/* Sector Display */}
                    {orderDetails.sector && (
                      <div>
                        <div className="mb-2">
                          <span className="text-sm font-medium ${getThemeClasses('text-secondary')}">
                            Event Sector:
                          </span>
                        </div>
                        <Badge variant="success" size="lg">
                          {getEventOrderSectorLabel(orderDetails.sector)}
                        </Badge>
                      </div>
                    )}

                    {/* Required Specializations Display */}
                    {orderDetails.specializationIds &&
                      orderDetails.specializationIds.length > 0 && (
                        <div>
                          <SpecializationDisplay
                            values={orderDetails.specializationIds}
                            label="Required Specializations"
                            variant="secondary"
                            onUnauthorized={onUnauthorized}
                            className="mb-0"
                          />
                        </div>
                      )}

                    {/* Required Certifications Display */}
                    {orderDetails.certificationIds &&
                      orderDetails.certificationIds.length > 0 && (
                        <div>
                          <CertificationDisplay
                            values={orderDetails.certificationIds}
                            label="Required Certifications"
                            variant="info"
                            onUnauthorized={onUnauthorized}
                            className="mb-0"
                          />
                        </div>
                      )}

                    {/* Event Category Display */}
                    {orderDetails.eventCategoryId && (
                      <div>
                        <EventCategoryDisplay
                          values={[orderDetails.eventCategoryId]}
                          label="Event Category"
                          variant="primary"
                          onUnauthorized={onUnauthorized}
                          className="mb-0"
                        />
                      </div>
                    )}

                    {/* Additional Order Notes Display */}
                    {orderDetails.additionalOrderNotes &&
                      orderDetails.additionalOrderNotes.trim() && (
                        <div>
                          <div className="mb-2">
                            <span className="text-sm font-medium ${getThemeClasses('text-secondary')}">
                              Additional Order Notes:
                            </span>
                          </div>
                          <div className="bg-white border ${getThemeClasses('border-border')} rounded-lg p-3">
                            <p className="text-sm text-gray-800 whitespace-pre-wrap">
                              {orderDetails.additionalOrderNotes.trim()}
                            </p>
                          </div>
                        </div>
                      )}
                  </div>
                </div>
              </div>
            </Card>

            {/* Attachments Summary Card */}
            <Card>
              <div className="p-6">
                <div className="flex items-center mb-4">
                  <PaperClipIcon className="w-6 h-6 text-blue-600 mr-2" />
                  <h2 className="text-xl font-semibold ${getThemeClasses('text-primary')}">
                    Attachments
                  </h2>
                  <span className="ml-2 px-2 py-1 ${getThemeClasses('bg-muted')} ${getThemeClasses('text-secondary')} rounded-full text-sm">
                    {attachments.length}
                  </span>
                  <div className="ml-auto">
                    <Link to="/admin/event-orders/add/step-4">
                      <Button variant="secondary" size="sm">
                        Modify
                      </Button>
                    </Link>
                  </div>
                </div>

                {attachments.length === 0 ? (
                  <div className="text-center py-8">
                    <DocumentIcon className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                    <p className="${getThemeClasses('text-secondary')}">
                      No attachments uploaded
                    </p>
                    <p className="text-sm ${getThemeClasses('text-muted')} mt-1">
                      You can add attachments in Step 4 if needed
                    </p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {attachments.map((attachment) => {
                      const getFileTypeIcon = (fileType) => {
                        if (fileType?.startsWith("image/")) {
                          return (
                            <DocumentIcon className="w-6 h-6 text-green-500" />
                          );
                        } else if (fileType === "application/pdf") {
                          return (
                            <DocumentIcon className="w-6 h-6 text-red-500" />
                          );
                        } else if (
                          fileType?.includes("word") ||
                          fileType?.includes("document")
                        ) {
                          return (
                            <DocumentIcon className="w-6 h-6 text-blue-500" />
                          );
                        } else if (
                          fileType?.includes("sheet") ||
                          fileType?.includes("excel")
                        ) {
                          return (
                            <DocumentIcon className="w-6 h-6 text-green-600" />
                          );
                        } else {
                          return (
                            <DocumentIcon className="w-6 h-6 ${getThemeClasses('text-muted')}" />
                          );
                        }
                      };

                      const formatFileSize = (bytes) => {
                        if (bytes === 0) return "0 Bytes";
                        const k = 1024;
                        const sizes = ["Bytes", "KB", "MB", "GB"];
                        const i = Math.floor(Math.log(bytes) / Math.log(k));
                        return (
                          parseFloat((bytes / Math.pow(k, i)).toFixed(2)) +
                          " " +
                          sizes[i]
                        );
                      };

                      return (
                        <div
                          key={attachment.id}
                          className="flex items-center justify-between p-4 ${getThemeClasses('bg-muted')} rounded-lg border"
                        >
                          <div className="flex items-center space-x-3">
                            {getFileTypeIcon(attachment.filetype)}
                            <div>
                              <p className="font-medium ${getThemeClasses('text-primary')}">
                                {attachment.filename || attachment.title}
                              </p>
                              <div className="flex items-center space-x-4 text-sm ${getThemeClasses('text-muted')}">
                                <span>
                                  {formatFileSize(attachment.fileSize || 0)}
                                </span>
                                <span>{attachment.filetype}</span>
                                {attachment.createdAt && (
                                  <span>
                                    Uploaded:{" "}
                                    {formatDateForDisplay(attachment.createdAt)}
                                  </span>
                                )}
                              </div>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </Card>

            {/* Capacity Impact Alert */}
            {event.attendeeCapacity &&
              event.attendeeCount !== undefined &&
              orderDetails &&
              (() => {
                const currentRegistrations = event.attendeeCount;
                const newRegistrations = orderDetails.eventAttendeeCapacity;
                const totalAfterOrder = currentRegistrations + newRegistrations;
                const remainingAfterOrder =
                  event.attendeeCapacity - totalAfterOrder;
                const percentFullAfterOrder =
                  (totalAfterOrder / event.attendeeCapacity) * 100;

                if (remainingAfterOrder === 0) {
                  return (
                    <Alert type="warning" className="mb-6">
                      <strong>This order will fill the event!</strong> After
                      this order, the event will be at full capacity (
                      {totalAfterOrder}/{event.attendeeCapacity} attendees).
                    </Alert>
                  );
                } else if (
                  remainingAfterOrder <= 3 ||
                  percentFullAfterOrder >= 95
                ) {
                  return (
                    <Alert type="info" className="mb-6">
                      <strong>Event will be nearly full!</strong> After this
                      order, only {remainingAfterOrder} slots will remain out of{" "}
                      {event.attendeeCapacity} total capacity.
                    </Alert>
                  );
                } else if (percentFullAfterOrder >= 85) {
                  return (
                    <Alert type="info" className="mb-6">
                      <strong>Event filling up!</strong> After this order,{" "}
                      {remainingAfterOrder} slots will remain out of{" "}
                      {event.attendeeCapacity} total capacity.
                    </Alert>
                  );
                }
                return null;
              })()}

            {/* Confirmation Card */}
            <Card>
              <div className="p-6">
                <div className="flex items-center mb-4">
                  <InformationCircleIcon className="w-6 h-6 text-blue-600 mr-2" />
                  <h2 className="text-xl font-semibold ${getThemeClasses('text-primary')}">
                    Confirmation
                  </h2>
                </div>

                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                  <p className="text-sm text-blue-800">
                    You are about to create an event order for{" "}
                    <strong>
                      {customer.name ||
                        `${customer.firstName} ${customer.lastName}`}
                    </strong>{" "}
                    for the event <strong>{event.name}</strong> with{" "}
                    <strong>
                      {orderDetails.eventAttendeeCapacity}{" "}
                      {orderDetails.eventAttendeeCapacity === 1
                        ? "attendee"
                        : "attendees"}
                    </strong>
                    .
                  </p>
                  <p className="text-sm text-blue-700 mt-2">
                    Please review the information above and click "Create Event
                    Order" to proceed.
                  </p>
                </div>

                {/* Action Buttons */}
                <div className="flex justify-between">
                  <div className="flex gap-3">
                    <Button
                      variant="secondary"
                      onClick={handleBackToAdditionalDetails}
                      disabled={submitting}
                    >
                      <ArrowLeftIcon className="w-4 h-4 mr-1" />
                      Back to Additional Details
                    </Button>

                    <Button
                      variant="secondary"
                      onClick={handleStartOver}
                      disabled={submitting}
                    >
                      Start Over
                    </Button>
                  </div>

                  <div className="flex gap-3">
                    <Link to="/admin/event-orders">
                      <Button variant="secondary" disabled={submitting}>
                        Cancel
                      </Button>
                    </Link>

                    <Button
                      variant="primary"
                      onClick={handleSubmitOrder}
                      disabled={submitting}
                      className={
                        submitting ? "opacity-50 cursor-not-allowed" : ""
                      }
                      loading={submitting}
                    >
                      {submitting ? (
                        <>Creating Order...</>
                      ) : (
                        <>
                          <CheckCircleIcon className="w-5 h-5 mr-1" />
                          Create Event Order
                        </>
                      )}
                    </Button>
                  </div>
                </div>
              </div>
            </Card>
          </div>
        )}

        {/* Missing Data State */}
        {(!customer || !event) && error && (
          <Card>
            <div className="p-6 text-center">
              <ExclamationTriangleIcon className="mx-auto h-12 w-12 text-red-400 mb-4" />
              <h3 className="text-lg font-medium ${getThemeClasses('text-primary')} mb-2">
                Missing Information
              </h3>
              <p className="${getThemeClasses('text-secondary')} mb-6">
                Some required information is missing to complete the order.
              </p>
              <div className="flex justify-center gap-3">
                <Button variant="secondary" onClick={handleStartOver}>
                  Start Over
                </Button>
                <Link to="/admin/event-orders">
                  <Button variant="primary">Go to Event Orders</Button>
                </Link>
              </div>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

function AdminEventOrderAddStep5PageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminEventOrderAddStep5Page />
    </UIXThemeProvider>
  );
}

export default AdminEventOrderAddStep5PageWrapper;
