// File Path: monorepo/web/frontend/src/pages/Admin/EventOrder/Update/Page.jsx

import React, { useState, useEffect } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { useEventOrderManager } from "../../../../services/Services";
import {
  Button,
  Card,
  Alert,
  Spinner,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import { CustomerSelect, EventSelect } from "../../../../components/business";
import {
  ChevronRightIcon,
  ChartBarIcon,
  TicketIcon,
  PencilIcon,
  ArrowLeftIcon,
  UserIcon,
  CalendarIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";

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

  // State management
  const [eventOrder, setEventOrder] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [validationErrors, setValidationErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);

  // Form state
  const [selectedCustomerId, setSelectedCustomerId] = useState("");
  const [selectedEventId, setSelectedEventId] = useState("");

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

  // Load event order data on mount
  useEffect(() => {
    const fetchEventOrder = async () => {
      if (!eventOrderID) {
        setError("Event Order ID is required");
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        setError(null);

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

        // Set initial form values
        setSelectedCustomerId(eventOrderData.customerId || "");
        setSelectedEventId(eventOrderData.eventId || "");
      } catch (err) {
        if (process.env.NODE_ENV === "development") {
          console.error("Failed to load event order for update:", err);
        }
        if (err.message && err.message.includes("404")) {
          setError("Event order not found");
        } else if (err.message) {
          setError(`Failed to load event order: ${err.message}`);
        } else {
          setError(
            "An unexpected error occurred while loading the event order",
          );
        }
      } finally {
        setLoading(false);
      }
    };

    fetchEventOrder();
  }, [eventOrderID, eventOrderManager]);

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

    if (!selectedEventId) {
      errors.eventId = "Event is required";
    }

    if (!selectedCustomerId) {
      errors.customerId = "Customer is required";
    }

    setValidationErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validateForm()) {
      setError("Please correct the validation errors below");
      return;
    }

    try {
      setSubmitting(true);
      setError(null);
      setValidationErrors({});

      const updateData = {
        id: eventOrder.id,
        eventId: selectedEventId,
        customerId: selectedCustomerId,
      };

      const updatedEventOrder = await eventOrderManager.updateEventOrder(
        eventOrderID,
        updateData,
        onUnauthorized,
      );

      // Redirect to the detail page
      navigate(`/admin/event-order/${eventOrderID}`, {
        state: { message: "Event order updated successfully" },
      });
    } catch (err) {
      if (process.env.NODE_ENV === "development") {
        console.error("Failed to update event order:", err);
      }

      // Handle validation errors from backend
      if (err && typeof err === "object" && !err.message) {
        setValidationErrors(err);
        setError("Please correct the validation errors below");
      } else if (err.message) {
        setError(`Failed to update event order: ${err.message}`);
      } else {
        setError("An unexpected error occurred while updating the event order");
      }
    } finally {
      setSubmitting(false);
    }
  };

  // Show loading state
  if (loading) {
    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 event order...
            </p>
          </div>
        </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>
              <div className="flex items-center">
                <ChevronRightIcon
                  className={`w-5 h-5 ${getThemeClasses("text-muted")}`}
                />
                <Link
                  to={`/admin/event-order/${eventOrderID}`}
                  className={`ml-1 text-sm font-medium ${getThemeClasses("text-secondary")} hover:text-blue-600 md:ml-2`}
                >
                  Order #{eventOrder?.publicId || eventOrderID}
                </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`}
                >
                  Edit
                </span>
              </div>
            </li>
          </ol>
        </nav>

        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div>
              <h1
                className={`text-3xl font-bold ${getThemeClasses("text-primary")} flex items-center`}
              >
                <PencilIcon className="w-8 h-8 mr-3 text-blue-600" />
                Update Event Order #{eventOrder?.publicId || eventOrderID}
              </h1>
              <p className={`mt-2 ${getThemeClasses("text-secondary")}`}>
                Update the event and customer assignments for this order
              </p>
            </div>
            <div className="flex gap-3">
              <Link to={`/admin/event-order/${eventOrderID}`}>
                <Button variant="secondary">
                  <ArrowLeftIcon className="w-4 h-4 mr-1" />
                  Back to Details
                </Button>
              </Link>
            </div>
          </div>
        </div>

        {/* Error Messages */}
        {error && (
          <Alert type="error" className="mb-6">
            {error}
          </Alert>
        )}

        {/* Update Form */}
        {eventOrder && (
          <Card>
            <div className="p-6">
              <form onSubmit={handleSubmit} className="space-y-6">
                {/* Current Information Display */}
                <div
                  className={`${getThemeClasses("bg-info-light")} rounded-lg p-4 mb-6`}
                >
                  <h3
                    className={`text-lg font-medium ${getThemeClasses("text-primary")} mb-4 flex items-center`}
                  >
                    <TicketIcon className="w-5 h-5 text-blue-600 mr-2" />
                    Current Assignment
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <h4
                        className={`text-sm font-medium ${getThemeClasses("text-muted")} mb-1`}
                      >
                        Current Event
                      </h4>
                      <p
                        className={`font-semibold ${getThemeClasses("text-primary")}`}
                      >
                        {eventOrder.eventName}
                      </p>
                      <p
                        className={`text-sm ${getThemeClasses("text-secondary")}`}
                      >
                        ID: #{eventOrder.eventPublicID}
                      </p>
                    </div>
                    <div>
                      <h4
                        className={`text-sm font-medium ${getThemeClasses("text-muted")} mb-1`}
                      >
                        Current Customer
                      </h4>
                      <p
                        className={`font-semibold ${getThemeClasses("text-primary")}`}
                      >
                        {eventOrder.customerName ||
                          `${eventOrder.customerFirstName} ${eventOrder.customerLastName}`}
                      </p>
                      <p
                        className={`text-sm ${getThemeClasses("text-secondary")}`}
                      >
                        ID: #{eventOrder.customerPublicID}
                      </p>
                    </div>
                  </div>
                </div>

                {/* Event Selection */}
                <div>
                  <EventSelect
                    label={
                      <span className="flex items-center">
                        <CalendarIcon className="w-4 h-4 mr-1" />
                        Select New Event *
                      </span>
                    }
                    value={selectedEventId}
                    onChange={setSelectedEventId}
                    placeholder="Choose an event..."
                    required={true}
                    error={validationErrors.eventId}
                    onUnauthorized={onUnauthorized}
                    includeArchived={false}
                    forceRefresh={false}
                    className="w-full"
                  />
                </div>

                {/* Customer Selection */}
                <div>
                  <CustomerSelect
                    label={
                      <span className="flex items-center">
                        <UserIcon className="w-4 h-4 mr-1" />
                        Select New Customer *
                      </span>
                    }
                    value={selectedCustomerId}
                    onChange={setSelectedCustomerId}
                    placeholder="Choose a customer..."
                    required={true}
                    error={validationErrors.customerId}
                    onUnauthorized={onUnauthorized}
                    includeInactive={false}
                    forceRefresh={false}
                    className="w-full"
                  />
                </div>

                {/* Form Actions */}
                <div
                  className={`flex items-center justify-between pt-6 border-t ${getThemeClasses("border-border")}`}
                >
                  <div className={`text-sm ${getThemeClasses("text-muted")}`}>
                    * Required fields
                  </div>
                  <div className="flex gap-3">
                    <Link to={`/admin/event-order/${eventOrderID}`}>
                      <Button type="button" variant="secondary">
                        Cancel
                      </Button>
                    </Link>
                    <Button
                      type="submit"
                      variant="primary"
                      disabled={submitting}
                      loading={submitting}
                    >
                      {submitting ? (
                        <>Updating...</>
                      ) : (
                        <>
                          <CheckCircleIcon className="w-4 h-4 mr-1" />
                          Update Event Order
                        </>
                      )}
                    </Button>
                  </div>
                </div>
              </form>
            </div>
          </Card>
        )}

        {/* No Data State */}
        {!eventOrder && !loading && !error && (
          <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`}
              >
                Event Order Not Found
              </h3>
              <p className={`${getThemeClasses("text-secondary")} mb-6`}>
                The requested event order could not be found.
              </p>
              <Link to="/admin/event-orders">
                <Button variant="primary">Go to Event Orders List</Button>
              </Link>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

function AdminEventOrderUpdatePageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminEventOrderUpdatePage />
    </UIXThemeProvider>
  );
}

export default AdminEventOrderUpdatePageWrapper;
