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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import {
  useAuthManager,
  useDivisionWizardStorage,
} from "../../../../services/Services";
import {
  MapPinIcon,
  HomeIcon,
  TruckIcon,
  PhoneIcon,
  UserIcon,
  GlobeAltIcon,
  BuildingOffice2Icon,
  EnvelopeIcon,
} from "@heroicons/react/24/outline";
import {
  StaffWizardFormStep,
  UIXThemeProvider,
  useUIXTheme,
  Input,
  Select,
  Checkbox,
  FormSection,
  FormRow,
} from "../../../../components/UIX";

// PERFORMANCE: Move constants outside component
const WIZARD_STEPS = [
  { title: "Search" },
  { title: "Type" },
  { title: "Contact" },
  { title: "Address" },
  { title: "Additional" },
  { title: "Review" },
];

// Country options
const COUNTRY_OPTIONS = [
  { value: "CA", label: "Canada" },
  { value: "US", label: "United States" },
  { value: "MX", label: "Mexico" },
];

// PERFORMANCE: Region options moved outside component (170+ lines)
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" },
];

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

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

  switch (country) {
    case 'CA':
      return /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/.test(trimmed);
    case 'US':
      return /^\d{5}(-\d{4})?$/.test(trimmed);
    case 'MX':
      return /^\d{5}$/.test(trimmed);
    default:
      return trimmed.length > 0;
  }
};

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

function AdminDivisionAddStep4Page() {
  const navigate = useNavigate();
  const authManager = useAuthManager();
  const wizardStorage = useDivisionWizardStorage();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);

  // Address form data
  const [postalCode, setPostalCode] = useState("");
  const [addressLine1, setAddressLine1] = useState("");
  const [addressLine2, setAddressLine2] = useState("");
  const [city, setCity] = useState("");
  const [region, setRegion] = useState("ON");
  const [country, setCountry] = useState("CA");
  const [hasShippingAddress, setHasShippingAddress] = useState(false);

  // Shipping address data
  const [shippingName, setShippingName] = useState("");
  const [shippingPhone, setShippingPhone] = useState("");
  const [shippingEmail, setShippingEmail] = useState("");
  const [shippingCountry, setShippingCountry] = useState("CA");
  const [shippingRegion, setShippingRegion] = useState("ON");
  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'),
    bgCard: getThemeClasses('bg-card'),
    borderSecondary: getThemeClasses('border-secondary'),
  }), [getThemeClasses]);

  // SECURITY & PERFORMANCE: Authentication check and load existing data (run once on mount)
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    const step4Data = wizardStorage.getStepData("step4Data");
    if (step4Data) {
      setPostalCode(step4Data.postalCode || "");
      setAddressLine1(step4Data.addressLine1 || "");
      setAddressLine2(step4Data.addressLine2 || "");
      setCity(step4Data.city || "");
      setRegion(step4Data.region || "ON");
      setCountry(step4Data.country || "CA");
      setHasShippingAddress(step4Data.hasShippingAddress || false);
      setShippingName(step4Data.shippingName || "");
      setShippingPhone(step4Data.shippingPhone || "");
      setShippingEmail(step4Data.shippingEmail || "");
      setShippingCountry(step4Data.shippingCountry || "CA");
      setShippingRegion(step4Data.shippingRegion || "ON");
      setShippingCity(step4Data.shippingCity || "");
      setShippingAddressLine1(step4Data.shippingAddressLine1 || "");
      setShippingAddressLine2(step4Data.shippingAddressLine2 || "");
      setShippingPostalCode(step4Data.shippingPostalCode || "");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // PERFORMANCE: Memoized helper functions
  const getRegionOptions = useCallback((selectedCountry) => {
    switch (selectedCountry) {
      case "CA":
        return CANADA_REGION_OPTIONS;
      case "US":
        return US_REGION_OPTIONS;
      case "MX":
        return MEXICO_REGION_OPTIONS;
      default:
        return CANADA_REGION_OPTIONS;
    }
  }, []);

  const getRegionLabel = useCallback((selectedCountry) => {
    switch (selectedCountry) {
      case "CA":
        return "Province/Territory";
      case "US":
        return "State";
      case "MX":
        return "State";
      default:
        return "Province/Territory";
    }
  }, []);

  // PERFORMANCE: Memoize region options and labels
  const mailingRegionOptions = useMemo(() => getRegionOptions(country), [country, getRegionOptions]);
  const mailingRegionLabel = useMemo(() => getRegionLabel(country), [country, getRegionLabel]);
  const shippingRegionOptions = useMemo(() => getRegionOptions(shippingCountry), [shippingCountry, getRegionOptions]);
  const shippingRegionLabel = useMemo(() => getRegionLabel(shippingCountry), [shippingCountry, getRegionLabel]);

  // Handle country change - reset region to first available option
  const handleCountryChange = useCallback(
    (value, isShipping = false) => {
      const newCountry = value;
      const regionOptions = getRegionOptions(newCountry);

      if (isShipping) {
        setShippingCountry(newCountry);
        if (regionOptions.length > 0) {
          setShippingRegion(regionOptions[0].value);
        }
      } else {
        setCountry(newCountry);
        if (regionOptions.length > 0) {
          setRegion(regionOptions[0].value);
        }
      }
    },
    [getRegionOptions],
  );

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

    // Mailing address validation with trimming and length checks
    const trimmedAddress1 = addressLine1.trim();
    const trimmedAddress2 = addressLine2.trim();
    const trimmedCity = city.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 > 255) {
      newErrors.city = "City is too long (max 255 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 (trimmedAddress2 && trimmedAddress2.length > 255) {
      newErrors.addressLine2 = "Address line 2 is too long (max 255 characters)";
    }
    if (!trimmedPostalCode) {
      newErrors.postalCode = "Postal/ZIP code is required";
    } else if (!isValidPostalCode(trimmedPostalCode, country)) {
      newErrors.postalCode = `Please enter a valid ${country === 'CA' ? 'postal code (A1A 1A1)' : country === 'US' ? 'ZIP code (12345)' : 'postal code'}`;
    }

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

      if (!trimmedShippingName) {
        newErrors.shippingName = "Billing name is required";
      } else if (trimmedShippingName.length > 255) {
        newErrors.shippingName = "Name is too long (max 255 characters)";
      }
      if (!trimmedShippingPhone) {
        newErrors.shippingPhone = "Billing phone is required";
      } else if (!isValidPhone(trimmedShippingPhone)) {
        newErrors.shippingPhone = "Please enter a valid phone number";
      }
      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 > 255) {
        newErrors.shippingCity = "City is too long (max 255 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 (trimmedShippingAddress2 && trimmedShippingAddress2.length > 255) {
        newErrors.shippingAddressLine2 = "Address line 2 is too long (max 255 characters)";
      }
      if (!trimmedShippingPostalCode) {
        newErrors.shippingPostalCode = "Billing postal/ZIP code is required";
      } else if (!isValidPostalCode(trimmedShippingPostalCode, shippingCountry)) {
        newErrors.shippingPostalCode = `Please enter a valid ${shippingCountry === 'CA' ? 'postal code (A1A 1A1)' : shippingCountry === 'US' ? 'ZIP code (12345)' : 'postal code'}`;
      }
    }

    return newErrors;
  }, [
    country,
    region,
    city,
    addressLine1,
    addressLine2,
    postalCode,
    hasShippingAddress,
    shippingName,
    shippingPhone,
    shippingCountry,
    shippingRegion,
    shippingCity,
    shippingAddressLine1,
    shippingAddressLine2,
    shippingPostalCode,
    getRegionLabel,
  ]);

  // Handle form submission
  const handleSubmit = useCallback(
    () => {
      const validationErrors = validateForm();
      if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        window.scrollTo({ top: 0, behavior: 'smooth' });
        return;
      }

      setIsLoading(true);
      setErrors({});

      try {
        // SECURITY: Save address data with sanitization
        const addressData = {
          postalCode: sanitizeInput(postalCode),
          addressLine1: sanitizeInput(addressLine1),
          addressLine2: sanitizeInput(addressLine2),
          city: sanitizeInput(city),
          region,
          country,
          hasShippingAddress: Boolean(hasShippingAddress),
          shippingName: sanitizeInput(shippingName),
          shippingPhone: sanitizeInput(shippingPhone),
          shippingEmail: sanitizeInput(shippingEmail),
          shippingCountry,
          shippingRegion,
          shippingCity: sanitizeInput(shippingCity),
          shippingAddressLine1: sanitizeInput(shippingAddressLine1),
          shippingAddressLine2: sanitizeInput(shippingAddressLine2),
          shippingPostalCode: sanitizeInput(shippingPostalCode),
          timestamp: new Date().toISOString(),
        };

        wizardStorage.saveStepData("step4Data", addressData);

        // Navigate to next step
        navigate("/admin/divisions/add/step-5");
      } catch (error) {
        setErrors({
          submit: error.message || "Failed to save address information",
        });
      } finally {
        setIsLoading(false);
      }
    },
    [
      validateForm,
      postalCode,
      addressLine1,
      addressLine2,
      city,
      region,
      country,
      hasShippingAddress,
      shippingName,
      shippingPhone,
      shippingEmail,
      shippingCountry,
      shippingRegion,
      shippingCity,
      shippingAddressLine1,
      shippingAddressLine2,
      shippingPostalCode,
      wizardStorage,
      navigate,
    ],
  );

  // Handle cancel
  const handleCancel = useCallback(() => {
    wizardStorage.clearWizardData();
    navigate("/admin/divisions");
  }, [wizardStorage, navigate]);

  // Handle previous step
  const handlePrevious = useCallback(() => {
    navigate("/admin/divisions/add/step-3");
  }, [navigate]);

  // PERFORMANCE: Memoize actions
  const actions = useMemo(() => [
    {
      label: "Continue to Additional",
      onClick: handleSubmit,
      variant: "primary",
      disabled: isLoading,
      loading: isLoading,
    }
  ], [handleSubmit, isLoading]);

  return (
    <UIXThemeProvider>
      <StaffWizardFormStep
        wizardSteps={WIZARD_STEPS}
        currentStep={4}
        wizardTitle="Add New Division"
        wizardIcon={BuildingOffice2Icon}
        stepTitle="Address Information"
        stepSubtitle="Enter the address information for the division"
        errors={errors}
        isLoading={isLoading}
        showFormCard={false}
        contentMaxWidth="7xl"
        actionLayout="between"
        onBack={handlePrevious}
        onCancel={handleCancel}
        backLabel="Back to Contact"
        cancelLabel="Cancel"
        actions={actions}
      >
        {/* Mailing Address Section */}
        <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} 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')}`} />
            {hasShippingAddress ? "Mailing Address" : "Address Information"}
          </h3>
          <FormSection>
            <FormRow>
              <Select
                label="Country"
                value={country}
                onChange={(value) => handleCountryChange(value, false)}
                options={COUNTRY_OPTIONS}
                error={errors.country}
                required={true}
              />
            </FormRow>

            <FormRow columns={2}>
              <Select
                label={mailingRegionLabel}
                value={region}
                onChange={setRegion}
                options={mailingRegionOptions}
                error={errors.region}
                required={true}
              />
              <Input
                label="City"
                value={city}
                onChange={setCity}
                error={errors.city}
                required={true}
                placeholder="Enter city"
                maxLength={255}
              />
            </FormRow>

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

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

            <FormRow>
              <Input
                label="Postal/ZIP Code"
                value={postalCode}
                onChange={setPostalCode}
                error={errors.postalCode}
                required={true}
                placeholder="Enter postal/ZIP code"
                helperText={country === 'CA' ? 'Format: A1A 1A1' : country === 'US' ? 'Format: 12345 or 12345-6789' : ''}
              />
            </FormRow>
          </FormSection>
        </div>

        {/* Billing Address Toggle */}
        <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} 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 Options
          </h3>
          <FormSection>
            <FormRow>
              <Checkbox
                label="Division has different billing address"
                checked={hasShippingAddress}
                onChange={setHasShippingAddress}
                helperText="Check this if the billing address differs from the mailing address"
              />
            </FormRow>
          </FormSection>
        </div>

        {/* Billing Address Section */}
        {hasShippingAddress && (
          <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} 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 columns={2}>
                <Input
                  label="Billing Contact Name"
                  value={shippingName}
                  onChange={setShippingName}
                  error={errors.shippingName}
                  required={true}
                  placeholder="Enter contact name"
                  icon={UserIcon}
                  maxLength={255}
                />
                <Input
                  label="Billing Phone"
                  type="tel"
                  value={shippingPhone}
                  onChange={setShippingPhone}
                  error={errors.shippingPhone}
                  required={true}
                  placeholder="Enter phone number"
                  icon={PhoneIcon}
                />
              </FormRow>

              <FormRow>
                <Input
                  label="Billing Email"
                  type="email"
                  value={shippingEmail}
                  onChange={setShippingEmail}
                  error={errors.shippingEmail}
                  placeholder="Enter email address"
                  icon={EnvelopeIcon}
                />
              </FormRow>

              <FormRow>
                <Select
                  label="Country"
                  value={shippingCountry}
                  onChange={(value) => handleCountryChange(value, true)}
                  options={COUNTRY_OPTIONS}
                  error={errors.shippingCountry}
                  required={true}
                />
              </FormRow>

              <FormRow columns={2}>
                <Select
                  label={shippingRegionLabel}
                  value={shippingRegion}
                  onChange={setShippingRegion}
                  options={shippingRegionOptions}
                  error={errors.shippingRegion}
                  required={true}
                />
                <Input
                  label="City"
                  value={shippingCity}
                  onChange={setShippingCity}
                  error={errors.shippingCity}
                  required={true}
                  placeholder="Enter city"
                  maxLength={255}
                />
              </FormRow>

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

              <FormRow>
                <Input
                  label="Address Line 2"
                  value={shippingAddressLine2}
                  onChange={setShippingAddressLine2}
                  error={errors.shippingAddressLine2}
                  placeholder="Apartment, suite, unit, etc. (optional)"
                  maxLength={255}
                />
              </FormRow>

              <FormRow>
                <Input
                  label="Postal/ZIP Code"
                  value={shippingPostalCode}
                  onChange={setShippingPostalCode}
                  error={errors.shippingPostalCode}
                  required={true}
                  placeholder="Enter postal/ZIP code"
                  helperText={shippingCountry === 'CA' ? 'Format: A1A 1A1' : shippingCountry === 'US' ? 'Format: 12345 or 12345-6789' : ''}
                />
              </FormRow>
            </FormSection>
          </div>
        )}
      </StaffWizardFormStep>
    </UIXThemeProvider>
  );
}

export default AdminDivisionAddStep4Page;
