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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import {
  UIXThemeProvider,
  useUIXTheme,
  StaffWizardFormStep,
  FormSection,
  FormRow,
  Input,
  Select,
  Checkbox,
  Alert,
  Modal,
  Button,
} from "../../../../components/UIX";
import {
  BuildingOfficeIcon,
  MapPinIcon,
  HomeIcon,
  TruckIcon,
  ArrowRightIcon,
  GlobeAltIcon,
  UserIcon,
  PhoneIcon,
} from "@heroicons/react/24/outline";

// PERFORMANCE: Move constants outside component to prevent recreation
const COUNTRY_OPTIONS = [
  { value: "CA", label: "Canada" },
  { value: "US", label: "United States" },
  { value: "MX", label: "Mexico" },
];

const CANADA_REGION_OPTIONS = [
  { value: "AB", label: "Alberta" },
  { value: "BC", label: "British Columbia" },
  { value: "MB", label: "Manitoba" },
  { value: "NB", label: "New Brunswick" },
  { value: "NL", label: "Newfoundland and Labrador" },
  { value: "NS", label: "Nova Scotia" },
  { value: "ON", label: "Ontario" },
  { value: "PE", label: "Prince Edward Island" },
  { value: "QC", label: "Quebec" },
  { value: "SK", label: "Saskatchewan" },
  { value: "NT", label: "Northwest Territories" },
  { value: "NU", label: "Nunavut" },
  { value: "YT", label: "Yukon" },
];

const US_REGION_OPTIONS = [
  { value: "AL", label: "Alabama" },
  { value: "AK", label: "Alaska" },
  { value: "AZ", label: "Arizona" },
  { value: "AR", label: "Arkansas" },
  { value: "CA", label: "California" },
  { value: "CO", label: "Colorado" },
  { value: "CT", label: "Connecticut" },
  { value: "DE", label: "Delaware" },
  { value: "FL", label: "Florida" },
  { value: "GA", label: "Georgia" },
  { value: "HI", label: "Hawaii" },
  { value: "ID", label: "Idaho" },
  { value: "IL", label: "Illinois" },
  { value: "IN", label: "Indiana" },
  { value: "IA", label: "Iowa" },
  { value: "KS", label: "Kansas" },
  { value: "KY", label: "Kentucky" },
  { value: "LA", label: "Louisiana" },
  { value: "ME", label: "Maine" },
  { value: "MD", label: "Maryland" },
  { value: "MA", label: "Massachusetts" },
  { value: "MI", label: "Michigan" },
  { value: "MN", label: "Minnesota" },
  { value: "MS", label: "Mississippi" },
  { value: "MO", label: "Missouri" },
  { value: "MT", label: "Montana" },
  { value: "NE", label: "Nebraska" },
  { value: "NV", label: "Nevada" },
  { value: "NH", label: "New Hampshire" },
  { value: "NJ", label: "New Jersey" },
  { value: "NM", label: "New Mexico" },
  { value: "NY", label: "New York" },
  { value: "NC", label: "North Carolina" },
  { value: "ND", label: "North Dakota" },
  { value: "OH", label: "Ohio" },
  { value: "OK", label: "Oklahoma" },
  { value: "OR", label: "Oregon" },
  { value: "PA", label: "Pennsylvania" },
  { value: "RI", label: "Rhode Island" },
  { value: "SC", label: "South Carolina" },
  { value: "SD", label: "South Dakota" },
  { value: "TN", label: "Tennessee" },
  { value: "TX", label: "Texas" },
  { value: "UT", label: "Utah" },
  { value: "VT", label: "Vermont" },
  { value: "VA", label: "Virginia" },
  { value: "WA", label: "Washington" },
  { value: "WV", label: "West Virginia" },
  { value: "WI", label: "Wisconsin" },
  { value: "WY", label: "Wyoming" },
];

const MEXICO_REGION_OPTIONS = [
  { value: "AGU", label: "Aguascalientes" },
  { value: "BCN", label: "Baja California" },
  { value: "BCS", label: "Baja California Sur" },
  { value: "CAM", label: "Campeche" },
  { value: "CHP", label: "Chiapas" },
  { value: "CHH", label: "Chihuahua" },
  { value: "COA", label: "Coahuila" },
  { value: "COL", label: "Colima" },
  { value: "DIF", label: "Ciudad de México" },
  { value: "DUR", label: "Durango" },
  { value: "GUA", label: "Guanajuato" },
  { value: "GRO", label: "Guerrero" },
  { value: "HID", label: "Hidalgo" },
  { value: "JAL", label: "Jalisco" },
  { value: "MEX", label: "México" },
  { value: "MIC", label: "Michoacán" },
  { value: "MOR", label: "Morelos" },
  { value: "NAY", label: "Nayarit" },
  { value: "NLE", label: "Nuevo León" },
  { value: "OAX", label: "Oaxaca" },
  { value: "PUE", label: "Puebla" },
  { value: "QUE", label: "Querétaro" },
  { value: "ROO", label: "Quintana Roo" },
  { value: "SLP", label: "San Luis Potosí" },
  { value: "SIN", label: "Sinaloa" },
  { value: "SON", label: "Sonora" },
  { value: "TAB", label: "Tabasco" },
  { value: "TAM", label: "Tamaulipas" },
  { value: "TLA", label: "Tlaxcala" },
  { value: "VER", label: "Veracruz" },
  { value: "YUC", label: "Yucatán" },
  { value: "ZAC", label: "Zacatecas" },
];

// Wizard steps configuration
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: true, isCompleted: false },
  { id: 5, title: "Additional", subtitle: "Extra Info", isActive: false, isCompleted: false },
  { id: 6, title: "Review", subtitle: "Confirm", isActive: false, isCompleted: false },
];

// SECURITY: Input sanitization
const sanitizeInput = (input) => {
  if (typeof input !== 'string') return input;
  return input.trim().replace(/[<>]/g, '');
};

// SECURITY: Postal code validation
const isValidPostalCode = (code, country) => {
  if (!code) return false;

  switch (country) {
    case 'CA':
      // Canadian postal code: A1A 1A1
      return /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/.test(code);
    case 'US':
      // US ZIP code: 12345 or 12345-6789
      return /^\d{5}(-\d{4})?$/.test(code);
    case 'MX':
      // Mexican postal code: 12345
      return /^\d{5}$/.test(code);
    default:
      return code.length > 0;
  }
};

// SECURITY: Phone validation
const isValidPhone = (phone) => {
  const phoneRegex = /^[\d\s\-\(\)\+]+$/;
  return phoneRegex.test(phone) && phone.replace(/\D/g, '').length >= 10;
};

// PERFORMANCE: Memoized region options lookup
const getRegionOptions = (country) => {
  switch (country) {
    case "CA":
      return CANADA_REGION_OPTIONS;
    case "US":
      return US_REGION_OPTIONS;
    case "MX":
      return MEXICO_REGION_OPTIONS;
    default:
      return CANADA_REGION_OPTIONS;
  }
};

// PERFORMANCE: Memoized region label lookup
const getRegionLabel = (country) => {
  switch (country) {
    case "CA":
      return "Province/Territory";
    case "US":
      return "State";
    case "MX":
      return "State";
    default:
      return "Province/Territory";
  }
};

function AdminOrganizationAddStep4Page() {
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();
  const [showCancelWarning, setShowCancelWarning] = useState(false);
  const [errors, setErrors] = useState({});
  const [isInitialized, setIsInitialized] = useState(false);

  // Mailing address states
  const [postalCode, setPostalCode] = useState("");
  const [addressLine1, setAddressLine1] = useState("");
  const [addressLine2, setAddressLine2] = useState("");
  const [city, setCity] = useState("");
  const [region, setRegion] = useState("AB");
  const [country, setCountry] = useState("CA");

  // Billing address states
  const [hasShippingAddress, setHasShippingAddress] = useState(false);
  const [shippingName, setShippingName] = useState("");
  const [shippingPhone, setShippingPhone] = useState("");
  const [shippingCountry, setShippingCountry] = useState("CA");
  const [shippingRegion, setShippingRegion] = useState("AB");
  const [shippingCity, setShippingCity] = useState("");
  const [shippingAddressLine1, setShippingAddressLine1] = useState("");
  const [shippingAddressLine2, setShippingAddressLine2] = useState("");
  const [shippingPostalCode, setShippingPostalCode] = useState("");

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

  // SECURITY: Load and validate data on mount
  useEffect(() => {
    const initializeData = async () => {
      try {
        // Validate previous steps exist
        const step1Data = sessionStorage.getItem("step1Data");
        const step2Data = sessionStorage.getItem("step2Data");
        const step3Data = sessionStorage.getItem("step3Data");

        if (!step1Data || !step2Data || !step3Data) {
          navigate("/admin/organizations/add/step-1");
          return;
        }

        // Load Step 4 data if exists
        const step4Data = sessionStorage.getItem("step4Data");
        if (step4Data) {
          try {
            const parsed = JSON.parse(step4Data);

            // SECURITY: Sanitize loaded data
            setAddressLine1(sanitizeInput(parsed.addressLine1 || ""));
            setAddressLine2(sanitizeInput(parsed.addressLine2 || ""));
            setCity(sanitizeInput(parsed.city || ""));
            setRegion(parsed.region || "AB");
            setCountry(parsed.country || "CA");
            setPostalCode(sanitizeInput(parsed.postalCode || ""));
            setHasShippingAddress(Boolean(parsed.hasShippingAddress));
            setShippingName(sanitizeInput(parsed.shippingName || ""));
            setShippingPhone(sanitizeInput(parsed.shippingPhone || ""));
            setShippingCountry(parsed.shippingCountry || "CA");
            setShippingRegion(parsed.shippingRegion || "AB");
            setShippingCity(sanitizeInput(parsed.shippingCity || ""));
            setShippingAddressLine1(sanitizeInput(parsed.shippingAddressLine1 || ""));
            setShippingAddressLine2(sanitizeInput(parsed.shippingAddressLine2 || ""));
            setShippingPostalCode(sanitizeInput(parsed.shippingPostalCode || ""));
          } catch (error) {
            if (import.meta.env.DEV) {
              console.error("Step 4: Error parsing step data:", error);
            }
          }
        }

        setIsInitialized(true);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Step 4: Initialization error:", error);
        }
        navigate("/admin/organizations/add/step-1");
      }
    };

    initializeData();
  }, [navigate]);

  // PERFORMANCE: Memoize region options for mailing address
  const mailingRegionOptions = useMemo(() => getRegionOptions(country), [country]);
  const mailingRegionLabel = useMemo(() => getRegionLabel(country), [country]);

  // PERFORMANCE: Memoize region options for billing address
  const billingRegionOptions = useMemo(() => getRegionOptions(shippingCountry), [shippingCountry]);
  const billingRegionLabel = useMemo(() => getRegionLabel(shippingCountry), [shippingCountry]);

  // PERFORMANCE: Memoized event handlers
  const handleCountryChange = useCallback((value) => {
    setCountry(value);
    const regionOptions = getRegionOptions(value);
    if (regionOptions.length > 0) {
      setRegion(regionOptions[0].value);
    }
  }, []);

  const handleShippingCountryChange = useCallback((value) => {
    setShippingCountry(value);
    const regionOptions = getRegionOptions(value);
    if (regionOptions.length > 0) {
      setShippingRegion(regionOptions[0].value);
    }
  }, []);

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

  const handleConfirmCancel = useCallback(() => {
    setShowCancelWarning(false);
    try {
      sessionStorage.removeItem("step1Data");
      sessionStorage.removeItem("step2Data");
      sessionStorage.removeItem("step3Data");
      sessionStorage.removeItem("step4Data");
      sessionStorage.removeItem("step5Data");
      sessionStorage.removeItem("step6Data");
      sessionStorage.removeItem("WORKERY_ORGANIZATION_CREATION_STATE");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error clearing session storage:", error);
      }
    }
    navigate("/admin/organizations");
  }, [navigate]);

  const handleBack = useCallback(() => {
    // Save current state before going back
    const step4Data = {
      postalCode: sanitizeInput(postalCode),
      addressLine1: sanitizeInput(addressLine1),
      addressLine2: sanitizeInput(addressLine2),
      city: sanitizeInput(city),
      region,
      country,
      hasShippingAddress,
      shippingName: sanitizeInput(shippingName),
      shippingPhone: sanitizeInput(shippingPhone),
      shippingCountry,
      shippingRegion,
      shippingCity: sanitizeInput(shippingCity),
      shippingAddressLine1: sanitizeInput(shippingAddressLine1),
      shippingAddressLine2: sanitizeInput(shippingAddressLine2),
      shippingPostalCode: sanitizeInput(shippingPostalCode),
      timestamp: new Date().toISOString(),
    };

    try {
      sessionStorage.setItem("step4Data", JSON.stringify(step4Data));
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error saving step4Data:", error);
      }
    }

    navigate("/admin/organizations/add/step-3");
  }, [
    postalCode, addressLine1, addressLine2, city, region, country,
    hasShippingAddress, shippingName, shippingPhone, shippingCountry,
    shippingRegion, shippingCity, shippingAddressLine1, shippingAddressLine2,
    shippingPostalCode, navigate
  ]);

  // SECURITY: Enhanced validation
  const validateForm = useCallback(() => {
    const newErrors = {};

    // Mailing address validation
    const trimmedCity = city.trim();
    const trimmedAddress1 = addressLine1.trim();
    const trimmedPostalCode = postalCode.trim();

    if (!country) {
      newErrors.country = "Country is required";
    }

    if (!region) {
      newErrors.region = `${getRegionLabel(country)} is required`;
    }

    if (!trimmedCity) {
      newErrors.city = "City is required";
    } else if (trimmedCity.length > 100) {
      newErrors.city = "City name is too long (max 100 characters)";
    }

    if (!trimmedAddress1) {
      newErrors.addressLine1 = "Address line 1 is required";
    } else if (trimmedAddress1.length > 255) {
      newErrors.addressLine1 = "Address is too long (max 255 characters)";
    }

    if (!trimmedPostalCode) {
      newErrors.postalCode = country === "US" ? "ZIP code is required" : "Postal code is required";
    } else if (!isValidPostalCode(trimmedPostalCode, country)) {
      newErrors.postalCode = country === "US" ? "Invalid ZIP code format" : "Invalid postal code format";
    }

    // Billing address validation
    if (hasShippingAddress) {
      const trimmedShippingName = shippingName.trim();
      const trimmedShippingPhone = shippingPhone.trim();
      const trimmedShippingCity = shippingCity.trim();
      const trimmedShippingAddress1 = shippingAddressLine1.trim();
      const trimmedShippingPostalCode = shippingPostalCode.trim();

      if (!trimmedShippingName) {
        newErrors.shippingName = "Billing contact name is required";
      } else if (trimmedShippingName.length > 255) {
        newErrors.shippingName = "Name is too long (max 255 characters)";
      }

      if (!trimmedShippingPhone) {
        newErrors.shippingPhone = "Billing contact phone is required";
      } else if (!isValidPhone(trimmedShippingPhone)) {
        newErrors.shippingPhone = "Invalid phone number format (at least 10 digits)";
      }

      if (!shippingCountry) {
        newErrors.shippingCountry = "Billing country is required";
      }

      if (!shippingRegion) {
        newErrors.shippingRegion = `Billing ${getRegionLabel(shippingCountry)} is required`;
      }

      if (!trimmedShippingCity) {
        newErrors.shippingCity = "Billing city is required";
      } else if (trimmedShippingCity.length > 100) {
        newErrors.shippingCity = "City name is too long (max 100 characters)";
      }

      if (!trimmedShippingAddress1) {
        newErrors.shippingAddressLine1 = "Billing address line 1 is required";
      } else if (trimmedShippingAddress1.length > 255) {
        newErrors.shippingAddressLine1 = "Address is too long (max 255 characters)";
      }

      if (!trimmedShippingPostalCode) {
        newErrors.shippingPostalCode = shippingCountry === "US" ? "Billing ZIP code is required" : "Billing postal code is required";
      } else if (!isValidPostalCode(trimmedShippingPostalCode, shippingCountry)) {
        newErrors.shippingPostalCode = shippingCountry === "US" ? "Invalid ZIP code format" : "Invalid postal code format";
      }
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [
    country, region, city, addressLine1, postalCode,
    hasShippingAddress, shippingName, shippingPhone, shippingCountry,
    shippingRegion, shippingCity, shippingAddressLine1, shippingPostalCode
  ]);

  const handleNext = useCallback((e) => {
    e.preventDefault();

    if (!validateForm()) {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

    // SECURITY: Sanitize data before saving
    const step4Data = {
      postalCode: sanitizeInput(postalCode),
      addressLine1: sanitizeInput(addressLine1),
      addressLine2: sanitizeInput(addressLine2),
      city: sanitizeInput(city),
      region,
      country,
      hasShippingAddress,
      shippingName: sanitizeInput(shippingName),
      shippingPhone: sanitizeInput(shippingPhone),
      shippingCountry,
      shippingRegion,
      shippingCity: sanitizeInput(shippingCity),
      shippingAddressLine1: sanitizeInput(shippingAddressLine1),
      shippingAddressLine2: sanitizeInput(shippingAddressLine2),
      shippingPostalCode: sanitizeInput(shippingPostalCode),
      timestamp: new Date().toISOString(),
    };

    try {
      sessionStorage.setItem("step4Data", JSON.stringify(step4Data));
      navigate("/admin/organizations/add/step-5");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Step 4: Error saving data:", error);
      }
      setErrors({ message: "Failed to save data. Please try again." });
    }
  }, [
    validateForm, postalCode, addressLine1, addressLine2, city, region, country,
    hasShippingAddress, shippingName, shippingPhone, shippingCountry,
    shippingRegion, shippingCity, shippingAddressLine1, shippingAddressLine2,
    shippingPostalCode, navigate
  ]);

  // PERFORMANCE: Memoize actions configuration
  const actions = useMemo(() => [
    {
      label: "Continue to Additional Info",
      variant: "primary",
      icon: ArrowRightIcon,
      onClick: handleNext,
      disabled: false,
    }
  ], [handleNext]);

  // Show loading state
  if (!isInitialized) {
    return (
      <div className={`min-h-screen ${getThemeClasses('bg-gradient-primary')} flex items-center justify-center`}>
        <div className="text-center">
          <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.borderPrimary} mx-auto`}></div>
          <p className={`mt-4 ${themeClasses.textSecondary}`}>Loading...</p>
        </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={4}
          wizardTitle="Add New Organization"
          wizardIcon={BuildingOfficeIcon}
          stepTitle="Address Information"
          stepSubtitle="Enter mailing and billing address details"
          stepIcon={MapPinIcon}
          errors={errors}
          showFormCard={false}
          contentMaxWidth="7xl"
          actions={actions}
          onCancel={handleCancel}
          onBack={handleBack}
          actionLayout="end"
        >
          {/* Error Alert */}
          {Object.keys(errors).length > 0 && errors.message && (
            <Alert
              type="error"
              message={errors.message || "Please correct the errors below before proceeding"}
              className="mb-6"
              dismissible
              onDismiss={() => setErrors({})}
            />
          )}

          {/* Mailing Address Section */}
          <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${getThemeClasses('border-secondary')} p-6 mb-6`}>
            <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
              <HomeIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
              Mailing Address
            </h3>
            <FormSection>
              <FormRow cols={2}>
                <Select
                  label="Country"
                  value={country}
                  onChange={handleCountryChange}
                  options={COUNTRY_OPTIONS}
                  error={errors.country}
                  required={true}
                  icon={GlobeAltIcon}
                />
                <Select
                  label={mailingRegionLabel}
                  value={region}
                  onChange={setRegion}
                  options={mailingRegionOptions}
                  error={errors.region}
                  required={true}
                  icon={MapPinIcon}
                />
              </FormRow>

              <FormRow cols={2}>
                <Input
                  label="City"
                  value={city}
                  onChange={setCity}
                  placeholder="Enter city"
                  error={errors.city}
                  required={true}
                  maxLength={100}
                />
                <Input
                  label={country === "US" ? "ZIP Code" : "Postal Code"}
                  value={postalCode}
                  onChange={setPostalCode}
                  placeholder={country === "US" ? "Enter ZIP code" : "Enter postal code"}
                  error={errors.postalCode}
                  required={true}
                  maxLength={10}
                />
              </FormRow>

              <FormRow>
                <Input
                  label="Address Line 1"
                  value={addressLine1}
                  onChange={setAddressLine1}
                  placeholder="Enter street address"
                  error={errors.addressLine1}
                  required={true}
                  maxLength={255}
                />
              </FormRow>

              <FormRow>
                <Input
                  label="Address Line 2"
                  value={addressLine2}
                  onChange={setAddressLine2}
                  placeholder="Apartment, suite, etc. (optional)"
                  maxLength={255}
                />
              </FormRow>
            </FormSection>
          </div>

          {/* Billing Address Toggle */}
          <div className="mb-6">
            <Checkbox
              label="Has billing address different from mailing address"
              checked={hasShippingAddress}
              onChange={setHasShippingAddress}
            />
          </div>

          {/* Billing Address Section */}
          {hasShippingAddress && (
            <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${getThemeClasses('border-secondary')} p-6 mb-6`}>
              <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
                <TruckIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
                Billing Address
              </h3>
              <FormSection>
                <FormRow cols={2}>
                  <Input
                    label="Contact Name"
                    value={shippingName}
                    onChange={setShippingName}
                    placeholder="Billing contact name"
                    error={errors.shippingName}
                    required={true}
                    icon={UserIcon}
                    maxLength={255}
                  />
                  <Input
                    label="Contact Phone"
                    type="tel"
                    value={shippingPhone}
                    onChange={setShippingPhone}
                    placeholder="Billing contact phone"
                    error={errors.shippingPhone}
                    required={true}
                    icon={PhoneIcon}
                    maxLength={20}
                  />
                </FormRow>

                <FormRow cols={2}>
                  <Select
                    label="Country"
                    value={shippingCountry}
                    onChange={handleShippingCountryChange}
                    options={COUNTRY_OPTIONS}
                    error={errors.shippingCountry}
                    required={true}
                    icon={GlobeAltIcon}
                  />
                  <Select
                    label={billingRegionLabel}
                    value={shippingRegion}
                    onChange={setShippingRegion}
                    options={billingRegionOptions}
                    error={errors.shippingRegion}
                    required={true}
                    icon={MapPinIcon}
                  />
                </FormRow>

                <FormRow cols={2}>
                  <Input
                    label="City"
                    value={shippingCity}
                    onChange={setShippingCity}
                    placeholder="Enter billing city"
                    error={errors.shippingCity}
                    required={true}
                    maxLength={100}
                  />
                  <Input
                    label={shippingCountry === "US" ? "ZIP Code" : "Postal Code"}
                    value={shippingPostalCode}
                    onChange={setShippingPostalCode}
                    placeholder={shippingCountry === "US" ? "Enter ZIP code" : "Enter postal code"}
                    error={errors.shippingPostalCode}
                    required={true}
                    maxLength={10}
                  />
                </FormRow>

                <FormRow>
                  <Input
                    label="Address Line 1"
                    value={shippingAddressLine1}
                    onChange={setShippingAddressLine1}
                    placeholder="Enter billing street address"
                    error={errors.shippingAddressLine1}
                    required={true}
                    maxLength={255}
                  />
                </FormRow>

                <FormRow>
                  <Input
                    label="Address Line 2"
                    value={shippingAddressLine2}
                    onChange={setShippingAddressLine2}
                    placeholder="Apartment, suite, etc. (optional)"
                    maxLength={255}
                  />
                </FormRow>
              </FormSection>
            </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 AdminOrganizationAddStep4PageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminOrganizationAddStep4Page />
    </UIXThemeProvider>
  );
}

export default AdminOrganizationAddStep4PageWrapper;
