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

import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router";
import {
  useEventOrderWizardStorage,
  useEventManager,
} from "../../../../services/Services";
import {
  Button,
  Input,
  Card,
  Alert,
  Spinner,
  Badge,
  TextArea,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  ChevronRightIcon,
  ChartBarIcon,
  TicketIcon,
  CheckCircleIcon,
  ArrowLeftIcon,
  ArrowRightIcon,
  UserGroupIcon,
  ExclamationTriangleIcon,
  InformationCircleIcon,
} from "@heroicons/react/24/outline";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";
import { EVENT_ORDER_SECTOR_OPTIONS } from "../../../../constants/EventOrder";
import SpecializationDisplay from "../../../../components/business/displays/SpecializationDisplay";
import CertificationDisplay from "../../../../components/business/displays/CertificationDisplay";
import EventCategoryDisplay from "../../../../components/business/displays/EventCategoryDisplay";

function AdminEventOrderAddStep3Page() {
  const navigate = useNavigate();
  const wizardStorage = useEventOrderWizardStorage();
  const eventManager = useEventManager();
  const { getThemeClasses } = useUIXTheme();

  // State management
  const [customer, setCustomer] = useState(null);
  const [event, setEvent] = useState(null);
  const [eventDetails, setEventDetails] = useState(null);
  const [attendeeCount, setAttendeeCount] = useState(1);
  const [error, setError] = useState(null);
  const [validationErrors, setValidationErrors] = useState({});
  const [loading, setLoading] = useState(true);
  const [loadingEventDetails, setLoadingEventDetails] = useState(false);

  // Multi-select states for order requirements
  const [specializations, setSpecializations] = useState([]);
  const [certifications, setCertifications] = useState([]);
  const [eventCategory, setEventCategory] = useState("");
  const [sector, setSector] = useState("");
  const [additionalOrderNotes, setAdditionalOrderNotes] = useState("");

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

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

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

      setEventDetails(eventData);

      // Set event category from event details
      if (eventData.eventCategoryId) {
        setEventCategory(eventData.eventCategoryId);
      }

      // Set specializations from event details
      if (eventData.specializationIds) {
        setSpecializations(eventData.specializationIds);
      }

      // Set certifications from event details
      if (eventData.certificationIds) {
        setCertifications(eventData.certificationIds);
      }

      // Set sector from event details
      if (eventData.sector) {
        setSector(eventData.sector);
      }
    } catch (error) {
      if (process.env.NODE_ENV === "development") {
        console.error("Step3Page: Failed to load event details", error);
      }
      setError("Failed to load event details. Please try again.");
    } finally {
      setLoadingEventDetails(false);
    }
  };

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

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

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

    setCustomer(customerData);
    setEvent(eventData);

    // Load detailed event information from API
    if (eventData && eventData.id) {
      loadEventDetails(eventData.id);
    }

    // Check if we already have order details from previous visits (only for attendee count and notes)
    const existingOrderDetails = wizardStorage.getOrderDetails();
    if (existingOrderDetails) {
      if (existingOrderDetails.eventAttendeeCapacity) {
        setAttendeeCount(existingOrderDetails.eventAttendeeCapacity);
      }
      if (existingOrderDetails.additionalOrderNotes) {
        setAdditionalOrderNotes(existingOrderDetails.additionalOrderNotes);
      }
    }

    setLoading(false);
  }, [wizardStorage]);

  // Handle attendance count change
  const handleAttendeeCountChange = (e) => {
    const value = parseInt(e.target.value, 10);
    setAttendeeCount(isNaN(value) ? 1 : value);
    setValidationErrors({});
  };

  // Validate form inputs
  const validateForm = () => {
    const errors = {};

    // Validate attendance count (only editable field)
    if (!attendeeCount || attendeeCount < 1) {
      errors.attendeeCount = "Number of attendees must be at least 1";
    } else if (event?.attendeeCapacity) {
      const availableSlots =
        event.attendeeCapacity - (event.attendeeCount || 0);
      if (attendeeCount > availableSlots) {
        errors.attendeeCount = `Number of attendees cannot exceed ${availableSlots} (available slots)`;
      }
    }

    // Note: Event category, specializations, certifications, and sector are all read-only from event data

    return errors;
  };

  // Handle continue to next step
  const handleContinue = () => {
    setError(null);

    // Validate all form inputs
    const errors = validateForm();
    if (Object.keys(errors).length > 0) {
      setValidationErrors(errors);
      return;
    }

    // Save order details to wizard storage
    wizardStorage.setOrderDetails({
      eventAttendeeCapacity: attendeeCount,
      eventCategoryId: eventCategory,
      specializationIds: specializations,
      certificationIds: certifications,
      sector: parseInt(sector) || 1, // Convert to number for backend
      additionalOrderNotes: additionalOrderNotes.trim(),
    });

    // Navigate to additional details step
    navigate("/admin/event-orders/add/step-4");
  };

  // Handle going back to event selection
  const handleBackToEventSelection = () => {
    navigate("/admin/event-orders/add/step-2-search");
  };

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

  // Show loading state while checking wizard data or loading event details
  if (loading || loadingEventDetails) {
    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")}`}>
              {loadingEventDetails
                ? "Loading event details..."
                : "Loading order details..."}
            </p>
          </div>
        </div>
      </div>
    );
  }

  // Show error state if missing required data
  if (error && (!customer || !event)) {
    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">
          <Card>
            <div className="p-6 text-center">
              <ExclamationTriangleIcon
                className={`mx-auto h-12 w-12 ${getThemeClasses("text-muted")} mb-4`}
              />
              <h3
                className={`text-lg font-medium ${getThemeClasses("text-primary")} mb-2`}
              >
                Missing Information
              </h3>
              <p className={`${getThemeClasses("text-secondary")} mb-6`}>
                {error}
              </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>
    );
  }

  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">
        {/* 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 3: Order Requirements
          </h1>
          <p className={`mt-2 ${getThemeClasses("text-secondary")}`}>
            Define the attendance count, specializations, certifications, and
            event category for this 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")}`}
              >
                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")}`}
              >
                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-blue-600 rounded-full text-white text-sm font-bold">
                3
              </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 ${getThemeClasses("bg-muted")} rounded-full ${getThemeClasses("text-muted")} text-sm font-bold`}
              >
                4
              </div>
              <span
                className={`ml-2 text-sm font-medium ${getThemeClasses("text-muted")}`}
              >
                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 ${getThemeClasses("bg-muted")} rounded-full ${getThemeClasses("text-muted")} text-sm font-bold`}
              >
                5
              </div>
              <span
                className={`ml-2 text-sm font-medium ${getThemeClasses("text-muted")}`}
              >
                Review & Confirm
              </span>
            </div>
          </div>
        </div>

        {/* Error Messages */}
        {error && !loading && (
          <Alert
            type="error"
            dismissible
            onDismiss={() => setError(null)}
            className="mb-6"
          >
            {error}
          </Alert>
        )}

        {/* Order Summary */}
        {customer && event && (
          <div className="space-y-6">
            {/* Selected Customer Info */}
            <Card
              className={`${getThemeClasses("bg-success-light")} border-green-200`}
            >
              <div className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <h3
                      className={`text-sm font-medium ${getThemeClasses("text-primary")}`}
                    >
                      Selected Customer
                    </h3>
                    <p
                      className={`mt-1 text-sm ${getThemeClasses("text-primary")}`}
                    >
                      <strong>
                        {customer.name ||
                          `${customer.firstName} ${customer.lastName}`}
                      </strong>
                      {customer.email && (
                        <span
                          className={`ml-2 ${getThemeClasses("text-secondary")}`}
                        >
                          • {customer.email}
                        </span>
                      )}
                    </p>
                  </div>
                  <CheckCircleIcon className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </Card>

            {/* Selected Event Info */}
            <Card
              className={`${getThemeClasses("bg-success-light")} border-green-200`}
            >
              <div className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <h3
                      className={`text-sm font-medium ${getThemeClasses("text-primary")}`}
                    >
                      Selected Event
                    </h3>
                    <p
                      className={`mt-1 text-sm ${getThemeClasses("text-primary")}`}
                    >
                      <strong>{event.name}</strong>
                      {event.startDateTime && (
                        <span
                          className={`ml-2 ${getThemeClasses("text-secondary")}`}
                        >
                          • {formatDateForDisplay(event.startDateTime)}
                        </span>
                      )}
                    </p>
                    {event.attendeeCapacity && (
                      <div className="mt-1 space-y-1">
                        <p
                          className={`text-sm ${getThemeClasses("text-secondary")}`}
                        >
                          Total Capacity: {event.attendeeCapacity} attendees
                        </p>
                        {event.attendeeCount !== undefined && (
                          <>
                            <p
                              className={`text-sm ${getThemeClasses("text-secondary")}`}
                            >
                              Current Registrations: {event.attendeeCount}{" "}
                              attendees
                            </p>
                            <p
                              className={`text-sm font-medium ${getThemeClasses("text-primary")}`}
                            >
                              Available Slots:{" "}
                              {event.attendeeCapacity - event.attendeeCount}{" "}
                              attendees
                            </p>
                          </>
                        )}
                      </div>
                    )}
                  </div>
                  <CheckCircleIcon className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </Card>

            {/* Order Requirements Card (Read-Only from Event) */}
            <Card>
              <div className="p-6">
                <h2
                  className={`text-xl font-semibold ${getThemeClasses("text-primary")} mb-6`}
                >
                  Order Requirements
                </h2>
                <p className={`${getThemeClasses("text-secondary")} mb-6`}>
                  The following requirements are defined by the selected event
                  and cannot be modified.
                </p>

                <div className="space-y-6">
                  {/* Sector (Read-Only) */}
                  <div>
                    <label
                      className={`block text-sm font-medium ${getThemeClasses("text-secondary")} mb-2`}
                    >
                      Sector
                    </label>
                    <div
                      className={`px-4 py-3 ${getThemeClasses("bg-muted")} ${getThemeClasses("border-border")} border rounded-md`}
                    >
                      <span className={getThemeClasses("text-primary")}>
                        {sector
                          ? EVENT_ORDER_SECTOR_OPTIONS.find(
                              (opt) => opt.value === sector.toString(),
                            )?.label || "Not specified"
                          : "Not specified"}
                      </span>
                    </div>
                    <p
                      className={`mt-1 text-sm ${getThemeClasses("text-muted")}`}
                    >
                      Sector is defined by the event
                    </p>
                  </div>

                  {/* Required Specializations (Read-Only) */}
                  <div>
                    <div
                      className={`px-4 py-3 ${getThemeClasses("bg-muted")} ${getThemeClasses("border-border")} border rounded-md`}
                    >
                      <SpecializationDisplay
                        values={specializations}
                        label="Required Specializations"
                        variant="primary"
                        onUnauthorized={onUnauthorized}
                        className="mb-0"
                      />
                    </div>
                    <p
                      className={`mt-1 text-sm ${getThemeClasses("text-muted")}`}
                    >
                      Specializations are defined by the event
                    </p>
                  </div>

                  {/* Required Certifications (Read-Only) */}
                  <div>
                    <div
                      className={`px-4 py-3 ${getThemeClasses("bg-muted")} ${getThemeClasses("border-border")} border rounded-md`}
                    >
                      <CertificationDisplay
                        values={certifications}
                        label="Required Certifications"
                        variant="info"
                        onUnauthorized={onUnauthorized}
                        className="mb-0"
                      />
                    </div>
                    <p
                      className={`mt-1 text-sm ${getThemeClasses("text-muted")}`}
                    >
                      Certifications are defined by the event
                    </p>
                  </div>

                  {/* Event Category (Read-Only) */}
                  <div>
                    <div
                      className={`px-4 py-3 ${getThemeClasses("bg-muted")} ${getThemeClasses("border-border")} border rounded-md`}
                    >
                      {eventCategory ? (
                        <EventCategoryDisplay
                          values={[eventCategory]}
                          label="Event Category"
                          variant="primary"
                          onUnauthorized={onUnauthorized}
                          className="mb-0"
                        />
                      ) : (
                        <span className={getThemeClasses("text-muted")}>
                          Loading event category...
                        </span>
                      )}
                    </div>
                    <p
                      className={`mt-1 text-sm ${getThemeClasses("text-muted")}`}
                    >
                      Event category is defined by the event
                    </p>
                  </div>

                  {/* Additional Order Notes */}
                  <TextArea
                    label="Additional Order Notes"
                    value={additionalOrderNotes}
                    onChange={setAdditionalOrderNotes}
                    placeholder="Enter any additional notes or special requirements for this event order"
                    required={false}
                    error={validationErrors.additionalOrderNotes}
                    helperText="Any additional information, special requirements, or notes for this event order (optional)"
                    rows={4}
                  />
                </div>
              </div>
            </Card>

            {/* Attendance Selection Card */}
            <Card>
              <div className="p-6">
                <div className="flex items-center mb-6">
                  <UserGroupIcon className="w-6 h-6 text-blue-600 mr-2" />
                  <h2
                    className={`text-xl font-semibold ${getThemeClasses("text-primary")}`}
                  >
                    Select Number of Attendees
                  </h2>
                </div>

                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
                  <div className="flex items-center">
                    <InformationCircleIcon className="w-5 h-5 text-blue-600 mr-2" />
                    <div className="text-sm text-blue-800">
                      {event.attendeeCapacity ? (
                        <>
                          <p>
                            This event has a total capacity of{" "}
                            <strong>{event.attendeeCapacity}</strong> attendees.
                          </p>
                          {event.attendeeCount !== undefined ? (
                            <p className="mt-1">
                              Currently <strong>{event.attendeeCount}</strong>{" "}
                              attendees are registered, leaving{" "}
                              <strong>
                                {event.attendeeCapacity - event.attendeeCount}
                              </strong>{" "}
                              available slots.
                            </p>
                          ) : (
                            <p className="mt-1">
                              You can select any number up to the total
                              capacity.
                            </p>
                          )}
                        </>
                      ) : (
                        "Select the number of attendees for this event order."
                      )}
                    </div>
                  </div>
                </div>

                {/* Capacity Warning */}
                {event.attendeeCapacity &&
                  event.attendeeCount !== undefined &&
                  (() => {
                    const availableSlots =
                      event.attendeeCapacity - event.attendeeCount;
                    const percentFull =
                      (event.attendeeCount / event.attendeeCapacity) * 100;

                    if (availableSlots === 0) {
                      return (
                        <Alert type="error" className="mb-6">
                          <strong>Event is Full!</strong> This event has reached
                          its capacity of {event.attendeeCapacity} attendees. No
                          new registrations can be accepted.
                        </Alert>
                      );
                    } else if (availableSlots <= 5 || percentFull >= 90) {
                      return (
                        <Alert type="warning" className="mb-6">
                          <strong>Limited Availability!</strong> Only{" "}
                          {availableSlots} slots remaining out of{" "}
                          {event.attendeeCapacity} total capacity.
                        </Alert>
                      );
                    } else if (percentFull >= 75) {
                      return (
                        <Alert type="info" className="mb-6">
                          <strong>Event Filling Up!</strong> {availableSlots}{" "}
                          slots remaining out of {event.attendeeCapacity} total
                          capacity.
                        </Alert>
                      );
                    }
                    return null;
                  })()}

                <div className="max-w-md">
                  <Input
                    label="Number of Attendees"
                    type="number"
                    value={attendeeCount}
                    onChange={handleAttendeeCountChange}
                    min={1}
                    max={
                      event.attendeeCapacity
                        ? event.attendeeCapacity - (event.attendeeCount || 0)
                        : 999
                    }
                    placeholder="Enter number of attendees"
                    icon={UserGroupIcon}
                    error={validationErrors.attendeeCount}
                    helperText={
                      event.attendeeCapacity
                        ? `Maximum: ${event.attendeeCapacity - (event.attendeeCount || 0)} available slots`
                        : "Enter the number of attendees"
                    }
                    required
                  />
                </div>

                {attendeeCount > 0 && (
                  <div
                    className={`mt-4 p-4 ${getThemeClasses("bg-muted")} rounded-lg`}
                  >
                    <div className="flex items-center justify-between">
                      <span
                        className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                      >
                        Selected Attendees:
                      </span>
                      <Badge variant="primary" size="lg">
                        {attendeeCount}{" "}
                        {attendeeCount === 1 ? "attendee" : "attendees"}
                      </Badge>
                    </div>
                    {event.attendeeCapacity && (
                      <div className="mt-2 space-y-1">
                        <div className="flex items-center justify-between">
                          <span
                            className={`text-sm ${getThemeClasses("text-secondary")}`}
                          >
                            Available Before This Order:
                          </span>
                          <span
                            className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                          >
                            {event.attendeeCapacity -
                              (event.attendeeCount || 0)}{" "}
                            slots
                          </span>
                        </div>
                        <div className="flex items-center justify-between">
                          <span
                            className={`text-sm ${getThemeClasses("text-secondary")}`}
                          >
                            Remaining After This Order:
                          </span>
                          <span
                            className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                          >
                            {event.attendeeCapacity -
                              (event.attendeeCount || 0) -
                              attendeeCount}{" "}
                            slots
                          </span>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Action Buttons */}
                <div
                  className={`mt-6 pt-6 border-t ${getThemeClasses("border-border")} flex justify-between`}
                >
                  <div className="flex gap-3">
                    <Button
                      variant="secondary"
                      onClick={handleBackToEventSelection}
                    >
                      <ArrowLeftIcon className="w-4 h-4 mr-1" />
                      Back to Event Selection
                    </Button>

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

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

                    <Button
                      variant="primary"
                      onClick={handleContinue}
                      disabled={
                        !attendeeCount ||
                        Object.keys(validationErrors).length > 0 ||
                        (event.attendeeCapacity &&
                          event.attendeeCount !== undefined &&
                          event.attendeeCapacity - event.attendeeCount === 0)
                      }
                    >
                      Continue to Additional Details
                      <ArrowRightIcon className="w-5 h-5 ml-2" />
                    </Button>
                  </div>
                </div>
              </div>
            </Card>
          </div>
        )}
      </div>
    </div>
  );
}

function AdminEventOrderAddStep3PageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminEventOrderAddStep3Page />
    </UIXThemeProvider>
  );
}

export default AdminEventOrderAddStep3PageWrapper;
