// monorepo/web/frontend/src/pages/Admin/Organization/Add/Step6Page.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import {
  useAuthManager,
  useOrganizationManager,
  useOrganizationWizardStorage,
} from "../../../../services/Services";
import { TagsDisplay } from "../../../../components/business/displays";
import {
  UIXThemeProvider,
  useUIXTheme,
  StaffWizardFormStep,
  Alert,
  Modal,
  Button,
} from "../../../../components/UIX";
import {
  CheckIcon,
  BuildingOfficeIcon,
  UserGroupIcon,
  HomeIcon,
  TruckIcon,
  QuestionMarkCircleIcon,
  Cog6ToothIcon,
  CheckCircleIcon,
} from "@heroicons/react/24/outline";

// PERFORMANCE: Move constants outside component
const WIZARD_STEPS = [
  { id: 1, title: "Search", subtitle: "Find Org", isActive: false, isCompleted: true },
  { id: 2, title: "Type", subtitle: "Select", isActive: false, isCompleted: true },
  { id: 3, title: "Contact", subtitle: "Information", isActive: false, isCompleted: true },
  { id: 4, title: "Address", subtitle: "Location", isActive: false, isCompleted: true },
  { id: 5, title: "Additional", subtitle: "Extra Info", isActive: false, isCompleted: true },
  { id: 6, title: "Review", subtitle: "Confirm", isActive: true, isCompleted: false },
];

// SECURITY: Sanitize output to prevent XSS
const sanitizeOutput = (value) => {
  if (typeof value !== 'string') return value;
  return value.trim();
};

// Detail Field Component
const DetailField = ({ label, value, fullWidth = false }) => {
  const { getThemeClasses } = useUIXTheme();

  return (
    <div className={fullWidth ? "lg:col-span-2" : ""}>
      <dt className={`text-base font-medium ${getThemeClasses('text-secondary')} mb-1`}>
        {label}
      </dt>
      <dd className={`text-lg font-medium ${getThemeClasses('text-primary')} break-words`}>
        {sanitizeOutput(value) || "-"}
      </dd>
    </div>
  );
};

function AdminOrganizationAddStep6Page() {
  const authManager = useAuthManager();
  const organizationManager = useOrganizationManager();
  const wizardStorage = useOrganizationWizardStorage();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [showCancelWarning, setShowCancelWarning] = useState(false);
  const [organizationData, setOrganizationData] = useState({});
  const [showSuccessMessage, setShowSuccessMessage] = useState(false);
  const [createdOrganizationId, setCreatedOrganizationId] = useState(null);

  // PERFORMANCE: Memoize theme classes
  const themeClasses = useMemo(() => ({
    textPrimary: getThemeClasses('text-primary'),
    textSecondary: getThemeClasses('text-secondary'),
    textMuted: getThemeClasses('text-muted'),
    bgCard: getThemeClasses('bg-card'),
    borderSecondary: getThemeClasses('border-secondary'),
    borderPrimary: getThemeClasses('border-primary'),
  }), [getThemeClasses]);

  // PERFORMANCE: Memoized helper functions
  const getOrganizationTypeLabel = useCallback((type) => {
    const typeMap = {
      educational: "Educational",
      corporate: "Corporate",
      "non-profit": "Non-Profit",
      government: "Government",
    };
    return typeMap[type] || type || "Unknown";
  }, []);

  const getPhoneTypeLabel = useCallback((phoneType) => {
    const typeMap = {
      0: "Unknown",
      1: "Mobile",
      2: "Work",
      3: "Home",
    };
    return typeMap[phoneType] || "Unknown";
  }, []);

  const getCountryLabel = useCallback((country) => {
    const countryMap = {
      CA: "Canada",
      US: "United States",
      MX: "Mexico",
    };
    return countryMap[country] || country || "Unknown";
  }, []);

  // SECURITY: Helper function to format and sanitize error field names
  const formatErrorFieldName = useCallback((key) => {
    // Handle contact array notation (e.g., "contacts[0].firstName")
    const contactMatch = key.match(/contacts\[(\d+)\]\.(.+)/);
    if (contactMatch) {
      const contactIndex = parseInt(contactMatch[1]) + 1;
      const fieldName = contactMatch[2];

      const fieldMappings = {
        firstName: "First Name",
        lastName: "Last Name",
        phoneType: "Phone Type",
        otherPhone: "Other Phone",
        otherPhoneType: "Other Phone Type",
        phoneExtension: "Phone Extension",
        otherPhoneExtension: "Other Phone Extension",
        isOkToEmail: "Email Consent",
      };

      const fieldNameFormatted =
        fieldMappings[fieldName] ||
        fieldName
          .replace(/([A-Z])/g, " $1")
          .replace(/^./, (str) => str.toUpperCase())
          .trim();

      return `Contact Person #${contactIndex} - ${fieldNameFormatted}`;
    }

    // Handle shipping/billing address fields
    if (key.startsWith("shipping")) {
      const fieldName = key.replace("shipping", "");
      const baseFieldMappings = {
        Name: "Billing Name",
        Phone: "Billing Phone",
        AddressLine1: "Billing Address Line 1",
        AddressLine2: "Billing Address Line 2",
        City: "Billing City",
        Region: "Billing Province/State",
        PostalCode: "Billing Postal/ZIP Code",
        Country: "Billing Country",
      };

      for (const [suffix, label] of Object.entries(baseFieldMappings)) {
        if (fieldName === suffix) {
          return label;
        }
      }
    }

    // Special field name mappings
    const fieldMappings = {
      organizationName: "Organization Name",
      organizationShortName: "Organization Short Name",
      organizationType: "Organization Type",
      addressLine1: "Address Line 1",
      addressLine2: "Address Line 2",
      city: "City",
      region: "Province/State",
      country: "Country",
      postalCode: "Postal/ZIP Code",
      hasShippingAddress: "Has Billing Address",
      tags: "Tags",
      joinDate: "Join Date",
      additionalComment: "Additional Comments",
      taxId: "Tax ID / Business Number",
      registrationNumber: "Registration Number",
      isActive: "Organization is Active",
      allowOnlineBookings: "Allow Online Bookings",
      requireApprovalForBookings: "Require Approval for Bookings",
    };

    return (
      fieldMappings[key] ||
      key
        .replace(/([A-Z])/g, " $1")
        .replace(/^./, (str) => str.toUpperCase())
        .trim()
    );
  }, []);

  // PERFORMANCE: Memoized event handlers
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  const loadOrganizationState = useCallback(() => {
    try {
      // Collect data from individual step keys
      const step1Data = wizardStorage.getStepData("step1Data") || {};
      const step2Data = wizardStorage.getStepData("step2Data") || {};
      const step3Data = wizardStorage.getStepData("step3Data") || {};
      const step4Data = wizardStorage.getStepData("step4Data") || {};
      const step5Data = wizardStorage.getStepData("step5Data") || {};

      // Combine all step data for display
      const combinedState = {
        ...step1Data,
        ...step2Data,
        ...step3Data,
        ...step4Data,
        ...step5Data,
      };

      // Validate we have required data
      if (!combinedState.organizationName || !combinedState.organizationType) {
        if (import.meta.env.DEV) {
          console.error("Step 6: Missing required data");
        }
        navigate("/admin/organizations/add/step-1");
        return;
      }

      setOrganizationData(combinedState);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Step 6: Error loading organization state:", error);
      }
      navigate("/admin/organizations/add/step-1");
    }
  }, [wizardStorage, navigate]);

  // Check authentication and load existing state
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    loadOrganizationState();
    window.scrollTo(0, 0);
  }, [authManager, navigate, loadOrganizationState]);

  const handleCancel = useCallback(() => {
    setShowCancelWarning(true);
  }, []);

  const handleConfirmCancel = useCallback(() => {
    wizardStorage.clearWizardData();
    navigate("/admin/organizations");
  }, [wizardStorage, navigate]);

  const handleBack = useCallback(() => {
    navigate("/admin/organizations/add/step-5");
  }, [navigate]);

  const onSubmitClick = useCallback(async (e) => {
    e.preventDefault();

    setIsLoading(true);
    setErrors({});

    try {
      // Validate wizard data
      const validation = wizardStorage.validateWizardData();

      if (!validation.isValid) {
        if (import.meta.env.DEV) {
          console.error("Step 6: Validation failed:", validation.errors);
        }
        setErrors(validation.errors);
        setIsLoading(false);
        window.scrollTo(0, 0);
        return;
      }

      // Transform data for API
      const apiData = wizardStorage.transformForAPI();

      // Submit using organization manager
      const createdOrganization = await organizationManager.createOrganization(
        apiData,
        onUnauthorized,
      );

      // Clear wizard data after successful submission
      wizardStorage.clearWizardData();

      // Set success state
      setCreatedOrganizationId(createdOrganization.id);
      setShowSuccessMessage(true);

      // Navigate to the new organization's detail page after a short delay
      setTimeout(() => {
        navigate(`/admin/organization/${createdOrganization.id}`);
      }, 2000);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Step 6: Error creating organization:", error);
      }

      // Handle API errors
      if (error && error.response && error.response.data) {
        setErrors(error.response.data);
      } else if (error && typeof error === "object" && !error.response) {
        setErrors(error);
      } else {
        setErrors({
          general:
            error.message || "Failed to create organization. Please try again.",
        });
      }

      setIsLoading(false);
      window.scrollTo(0, 0);
    }
  }, [wizardStorage, organizationManager, onUnauthorized, navigate]);

  // PERFORMANCE: Memoize error list
  const errorList = useMemo(() => {
    if (!errors || Object.keys(errors).length === 0) return null;

    return Object.entries(errors)
      .filter(([key]) => key !== "general")
      .sort(([a], [b]) => {
        const aIsContact = a.includes("contacts[");
        const bIsContact = b.includes("contacts[");
        if (aIsContact && !bIsContact) return -1;
        if (!aIsContact && bIsContact) return 1;
        return a.localeCompare(b);
      })
      .map(([key, value]) => {
        const fieldLabel = formatErrorFieldName(key);
        let errorMessage = value;

        // Normalize common error messages
        if (
          value === "missing value" ||
          value === "Required field" ||
          value === "required"
        ) {
          errorMessage = "This field is required";
        } else if (value === "invalid") {
          errorMessage = "Please enter a valid value";
        } else if (
          key.includes("email") &&
          (value.includes("invalid") || value.includes("format"))
        ) {
          errorMessage = "Please enter a valid email address";
        } else if (
          key.includes("phone") &&
          (value.includes("invalid") || value.includes("format"))
        ) {
          errorMessage = "Please enter a valid phone number";
        } else if (
          key.includes("postalCode") &&
          (value.includes("invalid") || value.includes("format"))
        ) {
          errorMessage = "Please enter a valid postal/ZIP code";
        }

        return { key, fieldLabel, errorMessage };
      });
  }, [errors, formatErrorFieldName]);

  // PERFORMANCE: Memoize actions configuration
  const actions = useMemo(() => [
    {
      label: "Create Organization",
      variant: "success",
      icon: CheckIcon,
      onClick: onSubmitClick,
      disabled: isLoading,
      type: "submit",
    }
  ], [onSubmitClick, isLoading]);

  // Show success message if organization was created
  if (showSuccessMessage) {
    return (
      <div className={`min-h-screen ${getThemeClasses('bg-gradient-primary')} flex items-center justify-center p-4`}>
        <div className={`${themeClasses.bgCard} rounded-lg shadow-lg p-8 max-w-md w-full text-center`}>
          <div className="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-green-100 mb-4">
            <CheckCircleIcon className="h-10 w-10 text-green-600" />
          </div>
          <h2 className={`text-2xl font-bold ${themeClasses.textPrimary} mb-2`}>
            Organization Created Successfully!
          </h2>
          <p className={`${themeClasses.textSecondary} mb-6`}>
            The organization has been created. Redirecting to organization details...
          </p>
          <div className={`animate-spin rounded-full h-8 w-8 border-b-2 ${themeClasses.borderPrimary} mx-auto`}></div>
        </div>
      </div>
    );
  }

  return (
    <div className={`min-h-screen ${getThemeClasses('bg-gradient-primary')} px-4 sm:px-6 lg:px-8`}>
      <div className="max-w-7xl mx-auto py-6 sm:py-8">
        <StaffWizardFormStep
          wizardSteps={WIZARD_STEPS}
          currentStep={6}
          wizardTitle="Add New Organization"
          wizardIcon={BuildingOfficeIcon}
          stepTitle="Review & Confirm"
          stepSubtitle="Review all information and create organization"
          stepIcon={CheckIcon}
          errors={errors}
          showFormCard={false}
          contentMaxWidth="7xl"
          actions={actions}
          onCancel={handleCancel}
          onBack={handleBack}
          actionLayout="end"
          isSubmitting={isLoading}
          submitButtonText="Create Organization"
        >
          {/* Error Alert */}
          {errorList && errorList.length > 0 && (
            <Alert
              type="error"
              message={errors.general || "Please correct the following errors before submitting:"}
              className="mb-6"
              dismissible
              onDismiss={() => setErrors({})}
            >
              <ul className="mt-2 space-y-1">
                {errorList.map(({ key, fieldLabel, errorMessage }) => (
                  <li key={key} className="text-sm">
                    • <span className="font-semibold">{fieldLabel}</span>:{" "}
                    <span>{errorMessage}</span>
                  </li>
                ))}
              </ul>
            </Alert>
          )}

          {/* Loading State */}
          {isLoading && (
            <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} p-8 mb-6`}>
              <div className="flex items-center justify-center">
                <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.borderPrimary}`}></div>
                <span className={`ml-3 ${themeClasses.textSecondary}`}>
                  Creating organization...
                </span>
              </div>
            </div>
          )}

          {/* Review Sections */}
          {!isLoading && (
            <>
              {/* Organization Information */}
              <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} mb-6`}>
                <div className={`px-6 py-4 border-b ${themeClasses.borderSecondary} flex justify-between items-center`}>
                  <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} flex items-center`}>
                    <BuildingOfficeIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                    Organization Information
                  </h3>
                  <button
                    type="button"
                    onClick={() => navigate("/admin/organizations/add/step-3")}
                    className={`text-sm ${getThemeClasses('text-link')} hover:underline`}
                  >
                    Edit
                  </button>
                </div>
                <div className="p-6">
                  <dl className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <DetailField
                      label="Organization Name"
                      value={organizationData.organizationName}
                    />
                    <DetailField
                      label="Short Name"
                      value={organizationData.organizationShortName}
                    />
                    <DetailField
                      label="Organization Type"
                      value={getOrganizationTypeLabel(organizationData.organizationType)}
                    />
                  </dl>
                </div>
              </div>

              {/* Contact Information */}
              <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} mb-6`}>
                <div className={`px-6 py-4 border-b ${themeClasses.borderSecondary} flex justify-between items-center`}>
                  <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} flex items-center`}>
                    <UserGroupIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                    Contact Information
                  </h3>
                  <button
                    type="button"
                    onClick={() => navigate("/admin/organizations/add/step-3")}
                    className={`text-sm ${getThemeClasses('text-link')} hover:underline`}
                  >
                    Edit
                  </button>
                </div>
                <div className="p-6">
                  {organizationData.contacts &&
                    organizationData.contacts.map((contact, index) => (
                      <div
                        key={index}
                        className={index > 0 ? `mt-6 pt-6 border-t ${themeClasses.borderSecondary}` : ""}
                      >
                        {organizationData.contacts.length > 1 && (
                          <p className={`text-sm font-semibold ${themeClasses.textSecondary} mb-4`}>
                            Contact Person #{index + 1}
                          </p>
                        )}
                        <dl className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                          <DetailField
                            label="Name"
                            value={`${contact.firstName || ""} ${contact.lastName || ""}`.trim()}
                          />
                          <DetailField label="Title" value={contact.title} />
                          <DetailField
                            label="Email"
                            value={contact.email || "Not provided"}
                          />
                          <DetailField
                            label="OK to Email"
                            value={contact.isOkToEmail ? "Yes" : "No"}
                          />
                          <DetailField
                            label="Phone"
                            value={
                              contact.phone
                                ? `${contact.phone} (${getPhoneTypeLabel(contact.phoneType)})`
                                : "-"
                            }
                          />
                          {contact.phoneType === 2 && contact.phoneExtension && (
                            <DetailField
                              label="Extension"
                              value={contact.phoneExtension}
                            />
                          )}
                          {contact.otherPhone && (
                            <>
                              <DetailField
                                label="Other Phone"
                                value={`${contact.otherPhone} (${getPhoneTypeLabel(contact.otherPhoneType)})`}
                              />
                              {contact.otherPhoneType === 2 &&
                                contact.otherPhoneExtension && (
                                  <DetailField
                                    label="Other Extension"
                                    value={contact.otherPhoneExtension}
                                  />
                                )}
                            </>
                          )}
                        </dl>
                      </div>
                    ))}
                </div>
              </div>

              {/* Mailing Address */}
              <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} mb-6`}>
                <div className={`px-6 py-4 border-b ${themeClasses.borderSecondary} flex justify-between items-center`}>
                  <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} flex items-center`}>
                    <HomeIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                    Mailing Address
                  </h3>
                  <button
                    type="button"
                    onClick={() => navigate("/admin/organizations/add/step-4")}
                    className={`text-sm ${getThemeClasses('text-link')} hover:underline`}
                  >
                    Edit
                  </button>
                </div>
                <div className="p-6">
                  <dl className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <DetailField
                      label="Address"
                      value={organizationData.addressLine1}
                    />
                    {organizationData.addressLine2 && (
                      <DetailField
                        label="Address Line 2"
                        value={organizationData.addressLine2}
                      />
                    )}
                    <DetailField label="City" value={organizationData.city} />
                    <DetailField
                      label="Province/Territory/State"
                      value={organizationData.region}
                    />
                    <DetailField
                      label="Postal/ZIP Code"
                      value={organizationData.postalCode}
                    />
                    <DetailField
                      label="Country"
                      value={getCountryLabel(organizationData.country)}
                    />
                  </dl>
                </div>
              </div>

              {/* Billing Address (if different) */}
              {organizationData.hasShippingAddress && (
                <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} mb-6`}>
                  <div className={`px-6 py-4 border-b ${themeClasses.borderSecondary} flex justify-between items-center`}>
                    <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} flex items-center`}>
                      <TruckIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                      Billing Address
                    </h3>
                    <button
                      type="button"
                      onClick={() => navigate("/admin/organizations/add/step-4")}
                      className={`text-sm ${getThemeClasses('text-link')} hover:underline`}
                    >
                      Edit
                    </button>
                  </div>
                  <div className="p-6">
                    <dl className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                      <DetailField
                        label="Name"
                        value={organizationData.shippingName}
                      />
                      <DetailField
                        label="Phone"
                        value={organizationData.shippingPhone}
                      />
                      <DetailField
                        label="Address"
                        value={organizationData.shippingAddressLine1}
                      />
                      {organizationData.shippingAddressLine2 && (
                        <DetailField
                          label="Address Line 2"
                          value={organizationData.shippingAddressLine2}
                        />
                      )}
                      <DetailField
                        label="City"
                        value={organizationData.shippingCity}
                      />
                      <DetailField
                        label="Province/Territory/State"
                        value={organizationData.shippingRegion}
                      />
                      <DetailField
                        label="Postal/ZIP Code"
                        value={organizationData.shippingPostalCode}
                      />
                      <DetailField
                        label="Country"
                        value={getCountryLabel(organizationData.shippingCountry)}
                      />
                    </dl>
                  </div>
                </div>
              )}

              {/* Additional Information */}
              <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} mb-6`}>
                <div className={`px-6 py-4 border-b ${themeClasses.borderSecondary} flex justify-between items-center`}>
                  <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} flex items-center`}>
                    <QuestionMarkCircleIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                    Additional Information
                  </h3>
                  <button
                    type="button"
                    onClick={() => navigate("/admin/organizations/add/step-5")}
                    className={`text-sm ${getThemeClasses('text-link')} hover:underline`}
                  >
                    Edit
                  </button>
                </div>
                <div className="p-6">
                  <dl className="space-y-4">
                    {/* Tags Display */}
                    {organizationData.tags && organizationData.tags.length > 0 && (
                      <div>
                        <TagsDisplay
                          values={organizationData.tags}
                          label="Tags"
                          onUnauthorized={onUnauthorized}
                          variant="success"
                        />
                      </div>
                    )}

                    {/* Tax ID and Registration Number */}
                    {(organizationData.taxId || organizationData.registrationNumber) && (
                      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        {organizationData.taxId && (
                          <DetailField
                            label="Tax ID / Business Number"
                            value={organizationData.taxId}
                          />
                        )}
                        {organizationData.registrationNumber && (
                          <DetailField
                            label="Registration Number"
                            value={organizationData.registrationNumber}
                          />
                        )}
                      </div>
                    )}

                    {/* Join Date */}
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                      <DetailField
                        label="Join Date"
                        value={organizationData.joinDate}
                      />
                    </div>

                    {/* Additional Comments */}
                    {organizationData.additionalComment && (
                      <div className={`mt-6 pt-6 border-t ${themeClasses.borderSecondary}`}>
                        <DetailField
                          label="Additional Comments"
                          value={organizationData.additionalComment}
                          fullWidth
                        />
                      </div>
                    )}
                  </dl>
                </div>
              </div>

              {/* Organization Settings */}
              <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} mb-6`}>
                <div className={`px-6 py-4 border-b ${themeClasses.borderSecondary} flex justify-between items-center`}>
                  <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} flex items-center`}>
                    <Cog6ToothIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                    Organization Settings
                  </h3>
                  <button
                    type="button"
                    onClick={() => navigate("/admin/organizations/add/step-5")}
                    className={`text-sm ${getThemeClasses('text-link')} hover:underline`}
                  >
                    Edit
                  </button>
                </div>
                <div className="p-6">
                  <dl className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <DetailField
                      label="Organization is Active"
                      value={organizationData.isActive !== undefined
                        ? (organizationData.isActive ? "Yes" : "No")
                        : "Yes"}
                    />
                    <DetailField
                      label="Allow Online Bookings"
                      value={organizationData.allowOnlineBookings ? "Yes" : "No"}
                    />
                    <DetailField
                      label="Require Approval for Bookings"
                      value={organizationData.requireApprovalForBookings ? "Yes" : "No"}
                    />
                  </dl>
                </div>
              </div>
            </>
          )}
        </StaffWizardFormStep>

        {/* Cancel Confirmation Modal */}
        <Modal
          isOpen={showCancelWarning}
          onClose={() => setShowCancelWarning(false)}
          title="Are you sure?"
          footer={
            <div className="flex justify-end space-x-3">
              <Button
                variant="secondary"
                onClick={() => setShowCancelWarning(false)}
              >
                No, Keep Working
              </Button>
              <Button
                variant="danger"
                onClick={handleConfirmCancel}
              >
                Yes, Cancel
              </Button>
            </div>
          }
        >
          <p className={themeClasses.textSecondary}>
            Your Organization record will be cancelled and your work will be
            lost. This cannot be undone. Do you want to continue?
          </p>
        </Modal>
      </div>
    </div>
  );
}

function AdminOrganizationAddStep6PageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminOrganizationAddStep6Page />
    </UIXThemeProvider>
  );
}

export default AdminOrganizationAddStep6PageWrapper;
