// File Path: monorepo/web/frontend/src/pages/Admin/EventOrder/Detail/More/Archive/Page.jsx

import React, { useState, useEffect } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
  ChevronRightIcon,
  ChartBarIcon,
  TicketIcon,
  EllipsisHorizontalIcon,
  ArchiveBoxIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  EyeIcon,
  DocumentTextIcon,
  ChatBubbleLeftRightIcon,
  PaperClipIcon,
  ArrowLeftIcon,
  InformationCircleIcon,
} from "@heroicons/react/24/outline";
import {
  useEventOrderManager,
  useAuthManager,
} from "../../../../../../services/Services";
import {
  Button,
  Card,
  Alert,
  Spinner,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../../../components/UIX";

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

  // Component states
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isFetching, setFetching] = useState(false);
  const [eventOrder, setEventOrder] = useState(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [alert, setAlert] = useState(null);

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

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

      if (!authManager.isAuthenticated()) {
        navigate("/login");
        return;
      }

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

        const eventOrderData = await eventOrderManager.getEventOrderDetail(
          eventOrderID,
          onUnauthorized,
        );
        setEventOrder(eventOrderData);
      } catch (err) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to load event order:", err);
        }
        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, authManager, eventOrderManager, navigate]);

  // Handle archive confirmation
  const handleConfirmArchive = async () => {
    setShowConfirmModal(false);
    setAlert(null);
    setFetching(true);

    try {
      await eventOrderManager.archiveEventOrder(eventOrderID, onUnauthorized);

      setAlert({
        type: "success",
        message: "Event order has been successfully archived!",
      });

      // Navigate to event orders list after a short delay
      setTimeout(() => {
        navigate("/admin/event-orders");
      }, 2000);
    } catch (err) {
      if (process.env.NODE_ENV === 'development') {
        console.error("Failed to archive event order:", err);
      }

      // Handle errors
      if (err && typeof err === "object") {
        setAlert({
          type: "error",
          message: err.message || err.general || "Failed to archive event order",
        });
      } else {
        setAlert({
          type: "error",
          message: "Failed to archive event order. Please try again.",
        });
      }
    } finally {
      setFetching(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 details...
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <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 text-gray-700 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 text-gray-400" />
                <Link
                  to="/admin/event-orders"
                  className="ml-1 text-sm font-medium text-gray-700 hover:text-blue-600 md:ml-2"
                >
                  Event Orders
                </Link>
              </div>
            </li>
            <li>
              <div className="flex items-center">
                <ChevronRightIcon className="w-5 h-5 text-gray-400" />
                <Link
                  to={`/admin/event-order/${eventOrderID}`}
                  className="ml-1 text-sm font-medium text-gray-700 hover:text-blue-600 md:ml-2"
                >
                  Order #{eventOrder?.publicId || eventOrderID}
                </Link>
              </div>
            </li>
            <li>
              <div className="flex items-center">
                <ChevronRightIcon className="w-5 h-5 text-gray-400" />
                <Link
                  to={`/admin/event-order/${eventOrderID}/more`}
                  className="ml-1 text-sm font-medium text-gray-700 hover:text-blue-600 md:ml-2"
                >
                  More Actions
                </Link>
              </div>
            </li>
            <li aria-current="page">
              <div className="flex items-center">
                <ChevronRightIcon className="w-5 h-5 text-gray-400" />
                <span className="ml-1 text-sm font-medium text-black md:ml-2">
                  Archive
                </span>
              </div>
            </li>
          </ol>
        </nav>

        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold text-black flex items-center">
                <TicketIcon className="w-8 h-8 mr-3 text-blue-600" />
                Event Order #{eventOrder?.publicId || eventOrderID}
              </h1>
              <p className="mt-2 text-gray-600">Archive event order</p>
            </div>
            <div className="flex gap-3">
              <Link to={`/admin/event-order/${eventOrderID}/more`}>
                <Button variant="secondary">
                  <ArrowLeftIcon className="w-4 h-4 mr-1" />
                  Back to More Actions
                </Button>
              </Link>
            </div>
          </div>
        </div>

        {/* Unified Tab Navigation */}
        {eventOrder && (
          <div className="mb-8">
            <div className="border-b border-gray-200">
              <nav className="-mb-px flex space-x-8">
                <Link
                  to={`/admin/event-order/${eventOrderID}`}
                  className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm flex items-center"
                >
                  <EyeIcon className="w-4 h-4 mr-2" />
                  Quick View
                </Link>
                <Link
                  to={`/admin/event-order/${eventOrderID}/full`}
                  className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm flex items-center"
                >
                  <DocumentTextIcon className="w-4 h-4 mr-2" />
                  Full Details
                </Link>
                <Link
                  to={`/admin/event-order/${eventOrderID}/comments`}
                  className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm flex items-center"
                >
                  <ChatBubbleLeftRightIcon className="w-4 h-4 mr-2" />
                  Comments
                </Link>
                <Link
                  to={`/admin/event-order/${eventOrderID}/attachments`}
                  className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm flex items-center"
                >
                  <PaperClipIcon className="w-4 h-4 mr-2" />
                  Attachments
                </Link>
                <Link
                  to={`/admin/event-order/${eventOrderID}/more`}
                  className="border-blue-500 text-blue-600 whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm flex items-center"
                >
                  <EllipsisHorizontalIcon className="w-4 h-4 mr-2" />
                  More Actions
                </Link>
              </nav>
            </div>
          </div>
        )}

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

        {/* Alert Messages */}
        {alert && (
          <Alert type={alert.type} className="mb-6">
            {alert.message}
          </Alert>
        )}

        {/* Status Alerts */}
        {eventOrder && eventOrder.status === 2 && (
          <Alert type="warning" className="mb-6">
            <ArchiveBoxIcon className="w-5 h-5 mr-2 inline" />
            This event order is already archived
          </Alert>
        )}

        {/* Main Content */}
        <Card>
          <div className="p-6">
            <div className="flex items-center mb-6">
              <ArchiveBoxIcon className="w-6 h-6 text-blue-600 mr-2" />
              <h2 className="text-xl font-semibold text-gray-900">
                Archive Event Order
              </h2>
            </div>

            {eventOrder && (
              <>
                {/* Warning Message */}
                <Alert type="warning" className="mb-6">
                  <ExclamationTriangleIcon className="w-6 h-6 mr-3 flex-shrink-0" />
                  <div className="flex-1">
                    <h3 className="text-lg font-semibold mb-2">
                      Archive Event Order - Are you sure?
                    </h3>
                    <p className="mb-3">
                      You are about to <strong>archive</strong> this event order.
                      This means:
                    </p>
                    <ul className="space-y-2 ml-4">
                      <li className="flex items-start">
                        <span className="inline-block w-2 h-2 bg-yellow-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></span>
                        The event order will no longer appear in the active list
                      </li>
                      <li className="flex items-start">
                        <span className="inline-block w-2 h-2 bg-yellow-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></span>
                        The event order will be moved to archived status
                      </li>
                      <li className="flex items-start">
                        <span className="inline-block w-2 h-2 bg-yellow-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></span>
                        All data will remain but the order will be marked as inactive
                      </li>
                      <li className="flex items-start">
                        <span className="inline-block w-2 h-2 bg-yellow-600 rounded-full mt-1.5 mr-2 flex-shrink-0"></span>
                        This action can be undone using the unarchive function
                      </li>
                    </ul>
                    <p className="mt-4 font-semibold">
                      Are you sure you would like to continue?
                    </p>
                  </div>
                </Alert>

                {/* Event Order Information */}
                <Card variant="secondary" className="mb-6">
                  <div className="p-4">
                    <h4 className="text-lg font-semibold text-gray-900 mb-4 flex items-center">
                      <InformationCircleIcon className="w-5 h-5 mr-2 text-gray-600" />
                      Event Order Information
                    </h4>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="flex items-center">
                        <span className="font-medium text-gray-700 mr-2">Order ID:</span>
                        <span className="text-gray-900">#{eventOrder.publicId}</span>
                      </div>
                      <div className="flex items-center">
                        <span className="font-medium text-gray-700 mr-2">Status:</span>
                        <span className={`font-medium ${eventOrder.status === 1 ? "text-green-600" : eventOrder.status === 2 ? "text-yellow-600" : "text-gray-500"}`}>
                          {eventOrder.status === 1 ? "Active" : eventOrder.status === 2 ? "Archived" : "Unknown"}
                        </span>
                      </div>
                      <div className="flex items-center">
                        <span className="font-medium text-gray-700 mr-2">Customer:</span>
                        <span className="text-gray-900">
                          {eventOrder.customerName || "N/A"}
                        </span>
                      </div>
                      <div className="flex items-center">
                        <span className="font-medium text-gray-700 mr-2">Event:</span>
                        <span className="text-gray-900">
                          {eventOrder.eventName || "N/A"}
                        </span>
                      </div>
                    </div>
                  </div>
                </Card>

                {/* Action Buttons */}
                <div className="flex justify-between pt-6">
                  <Link to={`/admin/event-order/${eventOrderID}/more`}>
                    <Button variant="secondary" disabled={isFetching}>
                      <ArrowLeftIcon className="w-4 h-4 mr-1" />
                      Cancel
                    </Button>
                  </Link>

                  <Button
                    variant="danger"
                    onClick={() => setShowConfirmModal(true)}
                    disabled={isFetching || eventOrder.status === 2}
                  >
                    <ArchiveBoxIcon className="w-4 h-4 mr-1" />
                    {eventOrder.status === 2 ? "Already Archived" : "Archive Event Order"}
                  </Button>
                </div>
              </>
            )}
          </div>
        </Card>

        {/* Confirmation Modal */}
        {showConfirmModal && (
          <div className="fixed inset-0 z-50 overflow-y-auto">
            <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
              {/* Background overlay */}
              <div
                className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
                onClick={() => setShowConfirmModal(false)}
              ></div>

              {/* Modal panel */}
              <div className="relative transform overflow-hidden rounded-lg bg-white text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg">
                <div className="bg-white px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
                  <div className="sm:flex sm:items-start">
                    <div className="mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-yellow-100 sm:mx-0 sm:h-10 sm:w-10">
                      <ExclamationTriangleIcon
                        className="h-6 w-6 text-yellow-600"
                        aria-hidden="true"
                      />
                    </div>
                    <div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left">
                      <h3 className="text-lg font-semibold leading-6 text-gray-900">
                        Confirm Archive
                      </h3>
                      <div className="mt-2">
                        <p className="text-sm text-gray-500">
                          <strong>Final Confirmation</strong>
                        </p>
                        <p className="mt-2 text-sm text-gray-500">
                          You are about to archive Event Order{" "}
                          <strong>#{eventOrder?.publicId}</strong>.
                        </p>
                        <p className="mt-2 text-sm text-gray-500">
                          This action will move the event order to archived status.
                          The action can be reversed using the unarchive function.
                        </p>
                        <p className="mt-3 text-sm font-medium text-yellow-600">
                          Are you sure you want to proceed?
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="bg-gray-50 px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6">
                  <Button
                    variant="danger"
                    onClick={handleConfirmArchive}
                    disabled={isFetching}
                    className="sm:ml-3"
                  >
                    {isFetching ? "Archiving..." : "Yes, Archive"}
                  </Button>
                  <Button
                    variant="secondary"
                    onClick={() => setShowConfirmModal(false)}
                    disabled={isFetching}
                  >
                    Cancel
                  </Button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function AdminEventOrderDetailMoreArchivePageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminEventOrderDetailMoreArchivePage />
    </UIXThemeProvider>
  );
}

export default AdminEventOrderDetailMoreArchivePageWrapper;