// File Path: monorepo/web/frontend/src/pages/Admin/EventContract/Add/Step4Page.jsx

import React, { useState, useEffect, useRef } from "react";
import { Link, useNavigate } from "react-router";
import {
  useEventContractWizardStorage,
  useEventContractManager,
} from "../../../../services/Services";
import {
  Button,
  Alert,
  Spinner,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  ChevronRightIcon,
  ChartBarIcon,
  TicketIcon,
  UserIcon,
  CalendarIcon,
  MapPinIcon,
  ClockIcon,
  CheckCircleIcon,
  ArrowLeftIcon,
  ExclamationTriangleIcon,
  LinkIcon,
  BuildingOfficeIcon,
  TagIcon,
  DocumentTextIcon,
  PencilSquareIcon,
  AcademicCapIcon,
  PaperClipIcon,
  BriefcaseIcon,
  PhoneIcon,
} from "@heroicons/react/24/outline";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";
import {
  getEventContractSectorLabel,
  getEventContractRoleTypeLabel,
} from "../../../../constants/EventContract";
import CertificationDisplay from "../../../../components/business/displays/CertificationDisplay";
import SpecializationDisplay from "../../../../components/business/displays/SpecializationDisplay";
import EventCategoryDisplay from "../../../../components/business/displays/EventCategoryDisplay";

function AdminEventContractStep4Page() {
  const navigate = useNavigate();
  const wizardStorage = useEventContractWizardStorage();
  const eventContractManager = useEventContractManager();
  const { getThemeClasses } = useUIXTheme();

  // State management
  const [facilitator, setFacilitator] = useState(null);
  const [event, setEvent] = useState(null);
  const [step2Data, setStep2Data] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const errorRef = useRef(null);

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

  // Scroll to error when it appears
  useEffect(() => {
    if (error && errorRef.current) {
      errorRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  }, [error]);

  // Load wizard data on mount
  useEffect(() => {
    const facilitatorData = wizardStorage.getFacilitator();
    const eventData = wizardStorage.getEvent();
    const contractData = wizardStorage.getWizardStep("step2");

    // Check if we have required data - only event is required now
    if (!eventData) {
      setError(
        "Event information is missing. Please select an event in step 1.",
      );
      return;
    }

    // Set facilitator if available (optional)
    if (facilitatorData) {
      setFacilitator(facilitatorData);
    }

    // Set contract data from Step2
    if (contractData) {
      setStep2Data(contractData);
    }

    setEvent(eventData);
  }, [wizardStorage]);

  // Handle contract submission
  const handleSubmitContract = async () => {
    if (!event) {
      setError(
        "Event information is missing. Please go back and select an event.",
      );
      return;
    }

    if (!step2Data) {
      setError("Contract details are missing. Please complete step 2 first.");
      return;
    }

    setSubmitting(true);
    setError(null);

    try {
      // Get temporary attachment IDs from wizard storage
      const temporaryAttachmentIds =
        wizardStorage.getWizardStep("temporaryAttachmentIds") || [];

      console.log("Step4Page: Debugging attachment IDs:", {
        temporaryAttachmentIds,
        type: typeof temporaryAttachmentIds,
        length: Array.isArray(temporaryAttachmentIds)
          ? temporaryAttachmentIds.length
          : "not array",
        wizardData: wizardStorage.getWizardStep("temporaryAttachmentIds"),
      });

      // Prepare the payload for EventContractManager (uses camelCase)
      const payload = {
        eventId: event.id,
        roleType: step2Data.roleType || 1, // Use the roleType from Step2
        sector: step2Data.sector || 1, // Use the sector from Step2
        eventCategoryId: step2Data.eventCategoryId || "", // Changed from eventCategoryIds to eventCategoryId (singular)
        specializationIds: step2Data.specializations || [],
        certificationIds: step2Data.certifications || [],
        locationNotes: step2Data.locationNotes || "",
        contactName: step2Data.contactName || "",
        contactNumber: step2Data.contactNumber || "",
        additionalContactNotes: step2Data.additionalContractNotes || "",
        estimatedContractHours: step2Data.estimatedContractHours || 0,
        temporaryAttachmentIds: temporaryAttachmentIds,
        // Note: facilitatorId is not required as facilitators are optional
      };

      console.log("Step4Page: Creating event contract with payload:", payload);
      console.log(
        "Step4Page: Attachment IDs being sent:",
        temporaryAttachmentIds,
      );

      // Create the event contract using EventContractManager
      const response = await eventContractManager.createEventContract(
        payload,
        onUnauthorized,
      );

      console.log("Event contract created successfully:", response);

      // Clear wizard data
      wizardStorage.clearWizardData();

      // Navigate to event contracts list with success message
      navigate("/admin/event-contracts", {
        state: {
          successMessage: "Event contract created successfully!",
          newContractId: response.id,
        },
      });
    } catch (err) {
      console.error("Failed to create event contract:", err);

      const formatFieldName = (fieldName) => {
        return fieldName
          .replace(/_/g, " ")
          .replace(/([A-Z])/g, " $1")
          .toLowerCase()
          .replace(/^./, (str) => str.toUpperCase());
      };

      // Handle specific field errors with user-friendly messages
      if (err.eventId) {
        setError(
          `Missing Event\n\nAn event must be selected to create a contract.\n\nPlease go back and select an event.`,
        );
      } else if (err.roleType) {
        setError(
          `Missing Role Type\n\nThe role type (Facilitator or Speaker) is required.\n\nPlease complete step 2 and select a role type.`,
        );
      } else if (err.sector) {
        setError(
          `Missing Sector\n\nThe sector information is required for this contract.\n\nPlease complete step 2 and select a sector.`,
        );
      } else if (err && typeof err === "object" && !err.message) {
        // Handle validation errors with multiple fields
        const errorFields = Object.keys(err);
        if (errorFields.length > 0) {
          const errorMessages = errorFields
            .map((field) => `• ${formatFieldName(field)}: ${err[field]}`)
            .join("\n");
          setError(
            `Validation Errors\n\nThe following fields have errors:\n\n${errorMessages}\n\nPlease correct these errors and try again.`,
          );
        } else {
          setError(
            "Unexpected Error\n\nPlease try again. If the problem persists, contact support.",
          );
        }
      } else if (err.message) {
        setError(err.message);
      } else if (err.detail) {
        setError(err.detail);
      } else if (typeof err === "string") {
        setError(err);
      } else {
        setError(
          "Unexpected Error\n\nAn unexpected error occurred while creating the contract. Please try again.",
        );
      }
    } finally {
      setSubmitting(false);
    }
  };

  // Handle going back to attachments
  const handleBackToAttachments = () => {
    navigate("/admin/event-contracts/add/step-3");
  };

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

  // Show loading state while checking wizard data
  if (!event && !error) {
    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 contract summary...
            </p>
          </div>
        </div>
      </div>
    );
  }

  // Review Section Component with Dark Header
  const ReviewSection = ({ title, icon: Icon, children, editLink }) => (
    <div
      className={`${getThemeClasses("card-header-bg")} rounded-lg shadow-sm mb-4 sm:mb-6`}
    >
      <div className="px-4 sm:px-6 py-3 sm:py-4 flex justify-between items-center">
        <h3
          className={`text-base sm:text-lg font-semibold ${getThemeClasses("text-primary")} flex items-center`}
        >
          <Icon
            className={`w-4 sm:w-5 h-4 sm:h-5 mr-2 ${getThemeClasses("text-accent")} flex-shrink-0`}
          />
          <span className="truncate">{title}</span>
        </h3>
        {editLink && (
          <Link
            to={editLink}
            className={`inline-flex items-center text-xs sm:text-sm ${getThemeClasses("link")}`}
          >
            <PencilSquareIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
            Edit
          </Link>
        )}
      </div>
      <div
        className={`${getThemeClasses("bg-card")} border-2 border-t-0 ${getThemeClasses("border-border")} rounded-b-lg p-4 sm:p-6`}
      >
        {children}
      </div>
    </div>
  );

  // Detail Field Component
  const DetailField = ({ label, value, fullWidth = false }) => (
    <div className={fullWidth ? "lg:col-span-2" : ""}>
      <dt
        className={`text-xs sm:text-sm font-medium ${getThemeClasses("text-secondary")} mb-1`}
      >
        {label}
      </dt>
      <dd
        className={`text-sm sm:text-base font-medium ${getThemeClasses("text-primary")} break-words`}
      >
        {value || "-"}
      </dd>
    </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-4">
        {/* 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")} ${getThemeClasses("link")}`}
              >
                <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-contracts"
                  className={`ml-1 text-sm font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("link")} md:ml-2`}
                >
                  Event Contracts
                </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 Contract
                </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 ${getThemeClasses("text-accent")}`}
            />
            Create Event Contract - Step 4: Review & Confirm
          </h1>
          <p className={`mt-2 ${getThemeClasses("text-secondary")}`}>
            Review your selections below and confirm to create the event
            contract.
          </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")}`}
              >
                Find 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")}`}
              >
                Contract
              </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")}`}
              >
                Attachments
              </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">
                4
              </div>
              <span
                className={`ml-2 text-sm font-medium ${getThemeClasses("text-primary")}`}
              >
                Review & Confirm
              </span>
            </div>
          </div>
        </div>

        {/* Error Messages */}
        {error && (
          <div ref={errorRef} className="mb-6">
            <Alert type="error" dismissible onDismiss={() => setError(null)}>
              <div className="flex">
                <div className="flex-shrink-0">
                  <ExclamationTriangleIcon className="h-5 w-5 text-red-400" />
                </div>
                <div className="ml-3 flex-1">
                  <h3 className="text-sm font-medium text-red-800">
                    Operation Failed
                  </h3>
                  <div className="mt-2 text-sm text-red-700">
                    <p className="whitespace-pre-wrap">{error}</p>
                  </div>
                </div>
              </div>
            </Alert>
          </div>
        )}

        {/* Main Content */}
        <div className={`${getThemeClasses("bg-card")} shadow-sm rounded-lg`}>
          {/* Dark Header */}
          <div className={`${getThemeClasses("card-header-bg")} rounded-t-lg`}>
            <div className="px-4 sm:px-6 py-3 sm:py-4">
              <h2
                className={`text-base sm:text-lg font-semibold ${getThemeClasses("text-primary")} flex items-center`}
              >
                <CheckCircleIcon
                  className={`w-4 sm:w-5 h-4 sm:h-5 mr-2 ${getThemeClasses("text-accent")} flex-shrink-0`}
                />
                Review and Submit
              </h2>
            </div>
          </div>

          {/* Content with Border */}
          <div
            className={`border-x-2 border-b-2 ${getThemeClasses("border-border")} rounded-b-lg p-4 sm:p-6`}
          >
            <p
              className={`text-sm sm:text-base ${getThemeClasses("text-secondary")} mb-6`}
            >
              Please carefully review the following contract details. If
              everything looks correct, click the{" "}
              <strong>Create Contract</strong> button to create the new event
              contract.
            </p>

            {loading ? (
              <div className="flex flex-col items-center justify-center py-8">
                <Spinner size="lg" />
                <p className={`mt-4 ${getThemeClasses("text-secondary")}`}>
                  Creating contract...
                </p>
              </div>
            ) : (
              <div className="space-y-0">
                {/* Event Details Section */}
                <ReviewSection
                  title="Event Details"
                  icon={CalendarIcon}
                  editLink="/admin/event-contracts/add/step-1-search"
                >
                  <dl className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                    <DetailField
                      label="Event Title"
                      value={(() => {
                        const name = event?.eventName || event?.name;
                        if (typeof name === "object") {
                          return (
                            name?.name ||
                            name?.title ||
                            name?.eventName ||
                            "Not specified"
                          );
                        }
                        return name || "Not specified";
                      })()}
                    />
                    <DetailField
                      label="Sector"
                      value={(() => {
                        if (typeof event?.type === "object") {
                          return (
                            event.type?.category ||
                            event.type?.description ||
                            "Not specified"
                          );
                        }
                        return event?.type || "Not specified";
                      })()}
                    />
                    <DetailField
                      label="Start Date & Time"
                      value={(() => {
                        if (event?.startDateTime || event?.startDate) {
                          let dateStr = formatDateForDisplay(
                            event.startDateTime || event.startDate,
                          );
                          if (event?.startTime) {
                            dateStr += ` at ${event.startTime}`;
                          }
                          return dateStr;
                        }
                        return "Not specified";
                      })()}
                    />
                    <DetailField
                      label="End Date & Time"
                      value={(() => {
                        if (event?.endDateTime || event?.endDate) {
                          let dateStr = formatDateForDisplay(
                            event.endDateTime || event.endDate,
                          );
                          if (event?.endTime) {
                            dateStr += ` at ${event.endTime}`;
                          }
                          return dateStr;
                        }
                        return "Not specified";
                      })()}
                    />
                    <DetailField
                      label="Event Type"
                      value={(() => {
                        const type = event?.type;
                        if (type === 1) return "Conference";
                        if (type === 2) return "In-School";
                        if (type === 3) return "Virtual";
                        return "Not specified";
                      })()}
                    />
                    <DetailField
                      label="Event Sector"
                      value={(() => {
                        const sector = event?.sector;
                        if (sector === 1) return "Public";
                        if (sector === 2) return "Private";
                        return "Not specified";
                      })()}
                    />
                    <DetailField
                      label="Partners"
                      value={event?.partners || "No partners specified"}
                      fullWidth
                    />
                    <DetailField
                      label="Event URL"
                      value={(() => {
                        const url =
                          event?.listingUrl ||
                          event?.listing_url ||
                          event?.url ||
                          event?.eventUrl ||
                          event?.websiteUrl;
                        if (url && typeof url === "string") {
                          return url;
                        }
                        if (typeof url === "object") {
                          return (
                            url?.url ||
                            url?.link ||
                            url?.href ||
                            "No URL provided"
                          );
                        }
                        return "No URL provided";
                      })()}
                      fullWidth
                    />
                    <DetailField
                      label="Event Location"
                      value={(() => {
                        const location = event?.location;
                        if (location) {
                          if (typeof location === "object") {
                            return (
                              location?.name ||
                              location?.address ||
                              location?.description ||
                              "Location specified"
                            );
                          }
                          return location;
                        }
                        return "Location not specified";
                      })()}
                      fullWidth
                    />
                  </dl>
                </ReviewSection>

                {/* Event Information Section */}
                <ReviewSection
                  title="Event Information"
                  icon={DocumentTextIcon}
                  editLink="/admin/event-contracts/add/step-1-search"
                >
                  <dl className="grid grid-cols-1 gap-4 sm:gap-6">
                    <DetailField
                      label="Description"
                      value={(() => {
                        const info =
                          event?.description ||
                          event?.additionalInfo ||
                          event?.notes;
                        if (typeof info === "object") {
                          return (
                            info?.description ||
                            info?.content ||
                            info?.text ||
                            "No additional information provided"
                          );
                        }
                        return info || "No additional information provided";
                      })()}
                      fullWidth
                    />
                    <DetailField
                      label="Attendee Capacity"
                      value={
                        event?.attendeeCapacity
                          ? `${event.attendeeCapacity} attendees`
                          : "Not specified"
                      }
                    />
                  </dl>

                  {/* Skill Sets Display */}
                  {event?.skillSets &&
                    Array.isArray(event.skillSets) &&
                    event.skillSets.length > 0 && (
                      <div
                        className={`pt-6 border-t ${getThemeClasses("border-border")}`}
                      >
                        <p
                          className={`text-sm font-semibold ${getThemeClasses("text-secondary")} mb-4 flex items-center`}
                        >
                          <AcademicCapIcon
                            className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`}
                          />
                          Required Skills
                        </p>
                        <div className="flex flex-wrap gap-2">
                          {event.skillSets.map((skill, index) => {
                            let skillName = "Unknown Skill";
                            if (typeof skill === "string") {
                              skillName = skill;
                            } else if (typeof skill === "object") {
                              skillName =
                                skill?.name ||
                                skill?.category ||
                                skill?.description ||
                                skill?.subCategory ||
                                `Skill ${index + 1}`;
                            }
                            return (
                              <span
                                key={index}
                                className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                              >
                                {skillName}
                              </span>
                            );
                          })}
                        </div>
                      </div>
                    )}
                </ReviewSection>

                {/* Contract Details Section */}
                <ReviewSection
                  title="Contract Details"
                  icon={BriefcaseIcon}
                  editLink="/admin/event-contracts/add/step-1-results"
                >
                  <dl className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                    <DetailField
                      label="Role Type"
                      value={(() => {
                        return (
                          getEventContractRoleTypeLabel(step2Data?.roleType) ||
                          "Not specified"
                        );
                      })()}
                    />
                    <DetailField
                      label="Sector"
                      value={(() => {
                        return (
                          getEventContractSectorLabel(step2Data?.sector) ||
                          "Not specified"
                        );
                      })()}
                    />
                    <DetailField label="Contract Status" value="Draft" />
                    <DetailField
                      label="Estimated Contract Hours"
                      value={
                        step2Data?.estimatedContractHours
                          ? `${step2Data.estimatedContractHours} hours`
                          : "Not specified"
                      }
                    />
                    {step2Data?.contactName && (
                      <DetailField
                        label="Contact Name"
                        value={step2Data.contactName}
                      />
                    )}
                    {step2Data?.contactNumber && (
                      <DetailField
                        label="Contact Number"
                        value={step2Data.contactNumber}
                      />
                    )}
                    {step2Data?.locationNotes && (
                      <DetailField
                        label="Location Notes"
                        value={step2Data.locationNotes}
                        fullWidth
                      />
                    )}
                    {step2Data?.additionalContractNotes && (
                      <DetailField
                        label="Additional Contract Notes"
                        value={step2Data.additionalContractNotes}
                        fullWidth
                      />
                    )}
                  </dl>

                  {/* Required Specializations Display */}
                  {step2Data?.specializations &&
                    step2Data.specializations.length > 0 && (
                      <div
                        className={`pt-6 border-t ${getThemeClasses("border-border")}`}
                      >
                        <SpecializationDisplay
                          values={step2Data.specializations}
                          label="Required Specializations"
                          variant="secondary"
                          onUnauthorized={onUnauthorized}
                          className="mb-0"
                        />
                      </div>
                    )}

                  {/* Required Certifications Display */}
                  {step2Data?.certifications &&
                    step2Data.certifications.length > 0 && (
                      <div
                        className={`pt-6 border-t ${getThemeClasses("border-border")}`}
                      >
                        <CertificationDisplay
                          values={step2Data.certifications}
                          label="Required Certifications"
                          variant="info"
                          onUnauthorized={onUnauthorized}
                          className="mb-0"
                        />
                      </div>
                    )}

                  {/* Event Category Display */}
                  {step2Data?.eventCategoryId && (
                    <div
                      className={`pt-6 border-t ${getThemeClasses("border-border")}`}
                    >
                      <EventCategoryDisplay
                        values={[step2Data.eventCategoryId]}
                        label="Event Category"
                        variant="primary"
                        onUnauthorized={onUnauthorized}
                        className="mb-0"
                      />
                    </div>
                  )}
                </ReviewSection>

                {/* Attachments Section */}
                <ReviewSection
                  title="Attachments"
                  icon={PaperClipIcon}
                  editLink="/admin/event-contracts/add/step-3"
                >
                  <div
                    className={`text-sm ${getThemeClasses("text-secondary")}`}
                  >
                    {(() => {
                      const attachmentIds =
                        wizardStorage.getWizardStep("temporaryAttachmentIds") ||
                        [];
                      const attachmentCount = Array.isArray(attachmentIds)
                        ? attachmentIds.length
                        : 0;

                      if (attachmentCount > 0) {
                        return `${attachmentCount} attachment${attachmentCount > 1 ? "s" : ""} uploaded`;
                      }
                      return "No attachments uploaded";
                    })()}
                  </div>
                </ReviewSection>

                {/* Form Actions */}
                <div className="flex flex-col sm:flex-row gap-3 mt-6">
                  <Button
                    variant="secondary"
                    onClick={handleStartOver}
                    disabled={submitting}
                    className="flex-1"
                  >
                    Start Over
                  </Button>
                  <Button
                    variant="secondary"
                    onClick={handleBackToAttachments}
                    disabled={submitting}
                    className="flex-1"
                  >
                    <ArrowLeftIcon className="w-4 h-4 mr-2" />
                    Back
                  </Button>
                  <Button
                    variant="primary"
                    onClick={handleSubmitContract}
                    disabled={submitting || !event}
                    className="flex-1"
                  >
                    {submitting ? (
                      <>
                        <Loading size="sm" className="mr-2" />
                        Creating Contract...
                      </>
                    ) : (
                      <>
                        <CheckCircleIcon className="w-4 sm:w-5 h-4 sm:h-5 mr-2" />
                        Create Contract
                      </>
                    )}
                  </Button>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Missing Data State */}
        {!event && error && (
          <div
            className={`${getThemeClasses("bg-card")} shadow-sm rounded-lg p-6 text-center`}
          >
            <ExclamationTriangleIcon
              className={`mx-auto h-12 w-12 ${getThemeClasses("text-danger")} mb-4`}
            />
            <h3
              className={`text-lg font-medium ${getThemeClasses("text-primary")} mb-2`}
            >
              Missing Information
            </h3>
            <p className={`${getThemeClasses("text-secondary")} mb-6`}>
              Event information is missing to complete the contract.
            </p>
            <div className="flex justify-center gap-3">
              <Button variant="secondary" onClick={handleStartOver}>
                Start Over
              </Button>
              <Link to="/admin/event-contracts">
                <Button variant="primary">Go to Event Contracts</Button>
              </Link>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default AdminEventContractStep4Page;
