// File Path: monorepo/web/frontend/src/pages/Admin/EventContract/Detail/More/Delete/Page.jsx

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

function AdminEventContractDetailMoreDeletePage() {
  const { eventContractID } = useParams();

  const navigate = useNavigate();
  const eventContractManager = useEventContractManager();
  const authManager = useAuthManager();

  // Component states
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [eventContract, setEventContract] = useState(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [alert, setAlert] = useState(null);
  const [submitting, setSubmitting] = useState(false);

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

  // Fetch event contract details on mount
  useEffect(() => {
    const fetchData = async () => {
      if (!eventContractID) {
        setError("Event Contract ID is required");
        setLoading(false);
        return;
      }

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

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

        const eventContractData =
          await eventContractManager.getEventContractDetail(
            eventContractID,
            onUnauthorized,
          );
        setEventContract(eventContractData);
      } catch (err) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to load data:", err);
        }
        if (err.message && err.message.includes("404")) {
          setError("Event contract not found");
        } else if (err.message) {
          setError(`Failed to load event contract: ${err.message}`);
        } else {
          setError(
            "An unexpected error occurred while loading the event contract",
          );
        }
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [eventContractID, authManager, eventContractManager, navigate]);

  // Handle delete confirmation
  const handleConfirmDelete = async () => {
    setShowConfirmModal(false);
    setAlert(null);
    setSubmitting(true);

    try {
      await eventContractManager.deleteEventContract(
        eventContractID,
        onUnauthorized,
      );
      setAlert({
        type: "success",
        message: "Event contract has been permanently deleted!",
      });

      // Redirect after showing success message
      setTimeout(() => {
        navigate("/admin/event-contracts");
      }, 2000);
    } catch (err) {
      if (process.env.NODE_ENV === 'development') {
        console.error("Failed to delete event contract:", err);
      }
      const errorMessage =
        err.message || "Failed to delete event contract. Please try again.";
      setAlert({ type: "error", message: errorMessage });
      setSubmitting(false);
    }
  };

  const { getThemeClasses } = useUIXTheme();

  // 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 contract 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 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-contracts"
                  className="ml-1 text-sm font-medium text-gray-700 hover:text-blue-600 md:ml-2"
                >
                  Event Contracts
                </Link>
              </div>
            </li>
            <li>
              <div className="flex items-center">
                <ChevronRightIcon className="w-5 h-5 text-gray-400" />
                <Link
                  to={`/admin/event-contract/${eventContractID}`}
                  className="ml-1 text-sm font-medium text-gray-700 hover:text-blue-600 md:ml-2"
                >
                  Contract #{eventContract?.publicId || eventContractID}
                </Link>
              </div>
            </li>
            <li>
              <div className="flex items-center">
                <ChevronRightIcon className="w-5 h-5 text-gray-400" />
                <Link
                  to={`/admin/event-contract/${eventContractID}/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">
                  Delete
                </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 Contract #{eventContract?.publicId || eventContractID}
              </h1>
              <p className="mt-2 text-gray-600">
                Delete event contract permanently
              </p>
            </div>
            <div className="flex gap-3">
              <Link to={`/admin/event-contract/${eventContractID}/more`}>
                <Button variant="secondary">
                  <ArrowLeftIcon className="w-4 h-4 mr-1" />
                  Back to More Actions
                </Button>
              </Link>
            </div>
          </div>
        </div>

        {/* Unified Tab Navigation */}
        {eventContract && (
          <div className="mb-8">
            <div className="bcontract-b bcontract-gray-200">
              <nav className="-mb-px flex space-x-8">
                <Link
                  to={`/admin/event-contract/${eventContractID}`}
                  className="bcontract-transparent text-gray-500 hover:text-gray-700 hover:bcontract-gray-300 whitespace-nowrap py-2 px-1 bcontract-b-2 font-medium text-sm flex items-center"
                >
                  <EyeIcon className="w-4 h-4 mr-2" />
                  Quick View
                </Link>
                <Link
                  to={`/admin/event-contract/${eventContractID}/full`}
                  className="bcontract-transparent text-gray-500 hover:text-gray-700 hover:bcontract-gray-300 whitespace-nowrap py-2 px-1 bcontract-b-2 font-medium text-sm flex items-center"
                >
                  <DocumentTextIcon className="w-4 h-4 mr-2" />
                  Full Details
                </Link>
                <Link
                  to={`/admin/event-contract/${eventContractID}/comments`}
                  className="bcontract-transparent text-gray-500 hover:text-gray-700 hover:bcontract-gray-300 whitespace-nowrap py-2 px-1 bcontract-b-2 font-medium text-sm flex items-center"
                >
                  <ChatBubbleLeftRightIcon className="w-4 h-4 mr-2" />
                  Comments
                </Link>
                <Link
                  to={`/admin/event-contract/${eventContractID}/attachments`}
                  className="bcontract-transparent text-gray-500 hover:text-gray-700 hover:bcontract-gray-300 whitespace-nowrap py-2 px-1 bcontract-b-2 font-medium text-sm flex items-center"
                >
                  <PaperClipIcon className="w-4 h-4 mr-2" />
                  Attachments
                </Link>
                <span className="bcontract-blue-500 text-blue-600 whitespace-nowrap py-2 px-1 bcontract-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">
              <TrashIcon className="w-6 h-6 text-red-600 mr-2" />
              <h2 className="text-xl font-semibold text-gray-900">
                Delete Event Contract
              </h2>
            </div>

            {eventContract && (
              <>
                {/* Critical Warning Message */}
                <Alert type="error" className="mb-6">
                  <div className="flex items-start">
                    <ShieldExclamationIcon className="w-6 h-6 text-red-600 mt-1 mr-3 flex-shrink-0" />
                    <div className="flex-1">
                      <h3 className="text-lg font-bold text-red-900 mb-2">
                        Delete Event Contract - Critical Action Warning
                      </h3>
                      <p className="text-red-700 font-semibold mb-3">
                        ⚠️ THIS IS A PERMANENT ACTION ⚠️
                      </p>
                      <p className="text-red-700 mb-3">
                        You are about to <strong>permanently delete</strong>{" "}
                        this event contract. This means:
                      </p>
                      <ul className="list-disc list-inside space-y-2 text-red-700">
                        <li>
                          All event contract data will be{" "}
                          <strong>permanently removed</strong> from the database
                        </li>
                        <li>
                          All related records, work contracts, and history will
                          be affected
                        </li>
                        <li>
                          The event contract will be{" "}
                          <strong>completely erased</strong>
                        </li>
                        <li>
                          This action <strong>CANNOT be undone</strong> without
                          database restoration
                        </li>
                        <li>
                          Recovery will require system administrator
                          intervention and may not be possible
                        </li>
                      </ul>
                      <p className="mt-4 text-red-800 font-bold">
                        ⚠️ Consider archiving instead if you want to preserve
                        the data but deactivate the record.
                      </p>
                    </div>
                  </div>
                </Alert>

                {/* Alternative Actions */}
                <Alert type="warning" className="mb-6">
                  <div className="flex items-start">
                    <LightBulbIcon className="w-6 h-6 text-amber-600 mt-1 mr-3 flex-shrink-0" />
                    <div className="flex-1">
                      <h4 className="text-lg font-semibold text-amber-900 mb-3">
                        Consider Alternative Actions
                      </h4>
                      <p className="text-amber-800 mb-3">
                        Before permanently deleting, consider these
                        alternatives:
                      </p>
                      <div className="space-y-3">
                        <div className="flex items-center">
                          <ArchiveBoxIcon className="w-5 h-5 text-amber-600 mr-2" />
                          <div>
                            <strong className="text-amber-900">Archive:</strong>
                            <span className="text-amber-800 ml-1">
                              Deactivates the record but preserves all data
                            </span>
                            <Link
                              to={`/admin/event-contract/${eventContractID}/more/archive`}
                              className="ml-2 text-blue-600 hover:text-blue-700 font-medium"
                            >
                              Archive instead →
                            </Link>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </Alert>

                {/* Event Contract Information */}
                <div className="bg-gray-50 rounded-lg p-6 mb-6">
                  <h4 className="text-lg font-semibold text-gray-900 mb-4">
                    Event Contract Information to be Deleted:
                  </h4>
                  <dl className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <dt className="text-sm font-medium text-gray-500">
                        Contract ID:
                      </dt>
                      <dd className="mt-1 text-sm text-gray-900">
                        #{eventContract.publicId || eventContractID}
                      </dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">
                        Description:
                      </dt>
                      <dd className="mt-1 text-sm text-gray-900">
                        {eventContract.description || "-"}
                      </dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">
                        Status:
                      </dt>
                      <dd className="mt-1 text-sm">
                        {eventContract.status === 1 ? (
                          <span className="text-green-600 font-medium">
                            Active
                          </span>
                        ) : eventContract.status === 2 ? (
                          <span className="text-amber-600 font-medium">
                            Archived
                          </span>
                        ) : (
                          <span className="text-gray-600">Unknown</span>
                        )}
                      </dd>
                    </div>
                    <div>
                      <dt className="text-sm font-medium text-gray-500">
                        Created:
                      </dt>
                      <dd className="mt-1 text-sm text-gray-900">
                        {eventContract.createdAt
                          ? new Date(
                              eventContract.createdAt,
                            ).toLocaleDateString()
                          : "-"}
                      </dd>
                    </div>
                  </dl>
                </div>

                {/* Action Buttons */}
                <div className="flex flex-col sm:flex-row justify-between gap-4">
                  <Link to={`/admin/event-contract/${eventContractID}/more`}>
                    <Button variant="secondary" disabled={submitting}>
                      <ArrowLeftIcon className="w-4 h-4 mr-2" />
                      Back to More Actions
                    </Button>
                  </Link>

                  <Button
                    variant="danger"
                    onClick={() => setShowConfirmModal(true)}
                    disabled={submitting}
                    loading={submitting}
                  >
                    <TrashIcon className="w-4 h-4 mr-2" />
                    Delete Permanently
                  </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={() => !submitting && 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">
                  {/* Modal Header */}
                  <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-red-100 sm:mx-0 sm:h-10 sm:w-10">
                      <ExclamationTriangleIcon className="h-6 w-6 text-red-600" />
                    </div>
                    <div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left flex-1">
                      <h3 className="text-lg font-semibold leading-6 text-gray-900 mb-2">
                        FINAL DELETE CONFIRMATION
                      </h3>

                      {/* Warning Banner */}
                      <div className="bg-red-50 bcontract bcontract-red-200 rounded-md p-3 mb-4">
                        <p className="text-sm text-red-800 font-bold text-center">
                          ⚠️ THIS ACTION CANNOT BE UNDONE ⚠️
                        </p>
                      </div>

                      <p className="text-sm text-gray-700 font-semibold mb-3">
                        You are about to permanently delete:
                      </p>

                      {/* Event Contract Details */}
                      <div className="bg-gray-50 rounded-md p-3 mb-4">
                        <dl className="space-y-1 text-sm">
                          <div>
                            <dt className="inline font-medium text-gray-500">
                              Contract ID:
                            </dt>
                            <dd className="inline ml-1 text-gray-900">
                              #{eventContract?.publicId || eventContractID}
                            </dd>
                          </div>
                          <div>
                            <dt className="inline font-medium text-gray-500">
                              Description:
                            </dt>
                            <dd className="inline ml-1 text-gray-900">
                              {eventContract?.description || "-"}
                            </dd>
                          </div>
                        </dl>
                      </div>

                      <p className="text-sm text-red-700 font-semibold mb-2">
                        All data related to this event contract will be
                        permanently erased.
                      </p>

                      <p className="text-sm text-gray-600 mb-4">
                        This includes all related records, comments,
                        attachments, and any other associated data.
                      </p>

                      <p className="text-sm text-red-800 font-bold">
                        Are you ABSOLUTELY CERTAIN you want to proceed?
                      </p>
                    </div>
                  </div>
                </div>

                {/* Modal Footer */}
                <div className="bg-gray-50 px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6 gap-3">
                  <Button
                    variant="danger"
                    onClick={handleConfirmDelete}
                    disabled={submitting}
                    loading={submitting}
                    className="w-full sm:w-auto"
                  >
                    {submitting ? "Deleting..." : "DELETE PERMANENTLY"}
                  </Button>
                  <Button
                    variant="secondary"
                    onClick={() => setShowConfirmModal(false)}
                    disabled={submitting}
                    className="w-full sm:w-auto"
                  >
                    Cancel - Keep Event Contract
                  </Button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function AdminEventContractDetailMoreDeletePageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminEventContractDetailMoreDeletePage />
    </UIXThemeProvider>
  );
}

export default AdminEventContractDetailMoreDeletePageWrapper;
