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

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

function AdminEventOrderDetailMoreUnarchivePage() {
  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 [eventOrder, setEventOrder] = useState(null);
  const [alert, setAlert] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [confirmationText, setConfirmationText] = useState("");

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

  // Fetch event order details on mount
  useEffect(() => {
    const fetchData = 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);

        // Check if event order is actually archived
        if (eventOrderData.status !== 2) {
          setError("This event order is not archived and cannot be unarchived.");
        }

        setEventOrder(eventOrderData);
      } catch (err) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to load data:", 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);
      }
    };

    fetchData();
  }, [eventOrderID, authManager, eventOrderManager, navigate]);

  // Handle unarchive submission
  const handleUnarchive = async () => {
    if (confirmationText !== "UNARCHIVE") {
      setAlert({ type: "error", message: "Please type UNARCHIVE to confirm this action." });
      return;
    }

    setSubmitting(true);
    setAlert(null);

    try {
      // Note: The same archiveEventOrder API is used, which toggles the archive status
      await eventOrderManager.archiveEventOrder(eventOrderID, onUnauthorized);
      setAlert({
        type: "success",
        message: "Event order has been successfully unarchived!",
      });

      // Redirect after showing success message
      setTimeout(() => {
        navigate("/admin/event-orders");
      }, 2000);
    } catch (err) {
      if (process.env.NODE_ENV === 'development') {
        console.error("Failed to unarchive event order:", err);
      }
      const errorMessage = err.message || "Failed to unarchive event order. Please try again.";
      setAlert({ type: "error", message: errorMessage });
      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 details...</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 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">
                  Unarchive
                </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">Restore event order from archive</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>
                <span 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
                </span>
              </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>
        )}

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

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

                {/* Warning Message */}
                <Alert type="warning" className="mb-6">
                  <div className="flex">
                    <ExclamationTriangleIcon className="w-5 h-5 text-amber-600 mr-3 flex-shrink-0 mt-0.5" />
                    <div>
                      <h3 className="text-sm font-medium text-amber-900 mb-2">
                        Important: Unarchiving Consequences
                      </h3>
                      <ul className="text-sm text-amber-700 space-y-1 list-disc list-inside">
                        <li>This event order will become active again</li>
                        <li>It will appear in active event order searches</li>
                        <li>All previous settings and data will be restored</li>
                        <li>It will be visible in the list again</li>
                      </ul>
                    </div>
                  </div>
                </Alert>

                {/* Event Order Information */}
                <div className="mb-6 bg-gray-50 rounded-lg p-4">
                  <h3 className="text-lg font-medium text-gray-900 mb-3">
                    Event Order Information
                  </h3>
                  <dl className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Order ID</dt>
                      <dd className="mt-1 text-sm text-gray-900">
                        #{eventOrder.publicId || eventOrderID}
                      </dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Description</dt>
                      <dd className="mt-1 text-sm text-gray-900">
                        {eventOrder.description || "-"}
                      </dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Status</dt>
                      <dd className="mt-1">
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                          <ArchiveBoxIcon className="w-3 h-3 mr-1" />
                          Archived
                        </span>
                      </dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">Created</dt>
                      <dd className="mt-1 text-sm text-gray-900">
                        {eventOrder.createdAt ? new Date(eventOrder.createdAt).toLocaleDateString() : "-"}
                      </dd>
                    </div>
                  </dl>
                </div>

                {/* Confirmation Section */}
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Type{" "}
                    <span className="font-mono bg-gray-100 px-2 py-1 rounded">
                      UNARCHIVE
                    </span>{" "}
                    to confirm
                  </label>
                  <input
                    type="text"
                    value={confirmationText}
                    onChange={(e) => setConfirmationText(e.target.value)}
                    placeholder="Type UNARCHIVE here"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    disabled={submitting}
                  />
                  <p className="mt-2 text-sm text-gray-500">
                    This action will restore the event order to active status and
                    make it visible again.
                  </p>
                </div>

                {/* Action Buttons */}
                <div className="flex flex-col sm:flex-row gap-3">
                  <Button
                    variant="success"
                    onClick={handleUnarchive}
                    disabled={submitting || confirmationText !== "UNARCHIVE"}
                    loading={submitting}
                  >
                    <ArchiveBoxXMarkIcon className="w-5 h-5 mr-2" />
                    Unarchive Event Order
                  </Button>

                  <Link to={`/admin/event-order/${eventOrderID}/more`}>
                    <Button variant="secondary" disabled={submitting}>
                      <XMarkIcon className="w-5 h-5 mr-2" />
                      Cancel
                    </Button>
                  </Link>
                </div>
              </>
            )}
          </div>
        </Card>

      </div>
    </div>
  );
}

function AdminEventOrderDetailMoreUnarchivePageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminEventOrderDetailMoreUnarchivePage />
    </UIXThemeProvider>
  );
}

export default AdminEventOrderDetailMoreUnarchivePageWrapper;
