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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import { useAuthManager } from "../../../../services/Services";
import {
  UserPlusIcon,
  ArrowLeftIcon,
  ArrowRightIcon,
  MapPinIcon,
  HomeIcon,
  TruckIcon,
  PhoneIcon,
  UserIcon,
  GlobeAltIcon,
} from "@heroicons/react/24/outline";
import {
  StepWizard,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Checkbox,
  Button,
  Alert,
  UIXThemeProvider,
} from "../../../../components/UIX";
import {
  CUSTOMER_COUNTRIES,
  CUSTOMER_COUNTRY_OPTIONS,
} from "../../../../constants/Customer";

// Memoize region options to prevent re-creation on every render
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" },
];

// Mexico region options
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", isCompleted: true },
  { id: 2, title: "Type", isCompleted: true },
  { id: 3, title: "Contact", isCompleted: true },
  { id: 4, title: "Address", isCompleted: false },
  { id: 5, title: "Account", isCompleted: false },
  { id: 6, title: "Comments", isCompleted: false },
];

function AdminCustomerAddStep4Page() {
  const authManager = useAuthManager();
  const navigate = useNavigate();

  // Get existing customer data from sessionStorage
  const [customerData, setCustomerData] = useState(() => {
    const saved = sessionStorage.getItem(
      "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
    );
    return saved ? JSON.parse(saved) : {};
  });

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

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

  // Shipping address data
  const [shippingName, setShippingName] = useState(
    customerData.shippingName || "",
  );
  const [shippingPhone, setShippingPhone] = useState(
    customerData.shippingPhone || "",
  );
  const [shippingCountry, setShippingCountry] = useState(
    customerData.shippingCountry || CUSTOMER_COUNTRIES.CA,
  );
  const [shippingRegion, setShippingRegion] = useState(
    customerData.shippingRegion || "ON",
  );
  const [shippingCity, setShippingCity] = useState(
    customerData.shippingCity || "",
  );
  const [shippingAddressLine1, setShippingAddressLine1] = useState(
    customerData.shippingAddressLine1 || "",
  );
  const [shippingAddressLine2, setShippingAddressLine2] = useState(
    customerData.shippingAddressLine2 || "",
  );
  const [shippingPostalCode, setShippingPostalCode] = useState(
    customerData.shippingPostalCode || "",
  );

  useEffect(() => {
    window.scrollTo(0, 0);

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

    // Check if we have customer data, if not redirect to step 2
    const saved = sessionStorage.getItem(
      "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
    );
    if (!saved) {
      navigate("/admin/customers/add/step-2");
    }
  }, [authManager, navigate]);

  // Memoize region options based on selected country
  const getRegionOptions = useCallback((selectedCountry) => {
    switch (selectedCountry) {
      case CUSTOMER_COUNTRIES.CA:
        return CANADA_REGION_OPTIONS;
      case CUSTOMER_COUNTRIES.US:
        return US_REGION_OPTIONS;
      case CUSTOMER_COUNTRIES.MX:
        return MEXICO_REGION_OPTIONS;
      default:
        return CANADA_REGION_OPTIONS;
    }
  }, []);

  // Memoize region label based on country
  const getRegionLabel = useCallback((selectedCountry) => {
    switch (selectedCountry) {
      case CUSTOMER_COUNTRIES.CA:
        return "Province/Territory";
      case CUSTOMER_COUNTRIES.US:
        return "State";
      case CUSTOMER_COUNTRIES.MX:
        return "State";
      default:
        return "Province/Territory";
    }
  }, []);

  // Handle country change - reset region to first available option
  const handleCountryChange = useCallback(
    (e, isShipping = false) => {
      const newCountry = e.target.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],
  );

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

    if (import.meta.env.DEV) {
      console.log("handleSubmit: Beginning...");
    }

    setErrors({});

    let newErrors = {};
    let hasErrors = false;

    // Billing address validation
    if (!country) {
      newErrors.country = "Country is required";
      hasErrors = true;
    }
    if (!region) {
      newErrors.region = `${getRegionLabel(country)} is required`;
      hasErrors = true;
    }
    if (!city.trim()) {
      newErrors.city = "City is required";
      hasErrors = true;
    }
    if (!addressLine1.trim()) {
      newErrors.addressLine1 = "Address line 1 is required";
      hasErrors = true;
    }
    if (!postalCode.trim()) {
      newErrors.postalCode = "Postal/ZIP code is required";
      hasErrors = true;
    }

    // Shipping address validation (if enabled)
    if (hasShippingAddress) {
      // Name and phone are optional for shipping address
      if (!shippingCountry) {
        newErrors.shippingCountry = "Shipping country is required";
        hasErrors = true;
      }
      if (!shippingRegion) {
        newErrors.shippingRegion = `Shipping ${getRegionLabel(shippingCountry)} is required`;
        hasErrors = true;
      }
      if (!shippingCity.trim()) {
        newErrors.shippingCity = "Shipping city is required";
        hasErrors = true;
      }
      if (!shippingAddressLine1.trim()) {
        newErrors.shippingAddressLine1 = "Shipping address line 1 is required";
        hasErrors = true;
      }
      if (!shippingPostalCode.trim()) {
        newErrors.shippingPostalCode = "Shipping postal/ZIP code is required";
        hasErrors = true;
      }
    }

    if (hasErrors) {
      setErrors(newErrors);
      window.scrollTo(0, 0);

      if (import.meta.env.DEV) {
        console.log("handleSubmit: Ending with error.");
      }
      return;
    }

    // Save to session storage
    const updatedCustomerData = {
      ...customerData,
      postalCode,
      addressLine1,
      addressLine2,
      city,
      region,
      country,
      hasShippingAddress,
      shippingName,
      shippingPhone,
      shippingCountry,
      shippingRegion,
      shippingCity,
      shippingAddressLine1,
      shippingAddressLine2,
      shippingPostalCode,
    };

    try {
      sessionStorage.setItem(
        "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
        JSON.stringify(updatedCustomerData),
      );
      setCustomerData(updatedCustomerData);

      if (import.meta.env.DEV) {
        console.log("handleSubmit: Ending with success.");
      }

      navigate("/admin/customers/add/step-5");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error saving customer state:", error);
      }
      setErrors({ general: "Failed to save data. Please try again." });
    }
  }, [
    customerData,
    postalCode,
    addressLine1,
    addressLine2,
    city,
    region,
    country,
    hasShippingAddress,
    shippingName,
    shippingPhone,
    shippingCountry,
    shippingRegion,
    shippingCity,
    shippingAddressLine1,
    shippingAddressLine2,
    shippingPostalCode,
    getRegionLabel,
    navigate,
  ]);

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

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={4}
        title="Add New Customer"
        icon={UserPlusIcon}
      >
      <form onSubmit={onSubmitClick}>
        {/* Error Alert */}
        {errors.general && (
          <Alert
            type="error"
            message={errors.general}
            onClose={() => setErrors({})}
            className="mb-6"
          />
        )}

        {/* Billing/Mailing Address Section */}
        <FormCard
          title={hasShippingAddress ? "Billing Address" : "Mailing Address"}
          icon={HomeIcon}
          description={
            hasShippingAddress
              ? "Primary billing address"
              : "Customer address details"
          }
          maxWidth="full"
          className="mb-6"
        >
          <FormSection>
            <FormRow columns={2}>
              <Select
                label="Country"
                name="country"
                value={country}
                onChange={(value) => {
                  const regionOptions = getRegionOptions(value);
                  setCountry(value);
                  if (regionOptions.length > 0) {
                    setRegion(regionOptions[0].value);
                  }
                }}
                options={CUSTOMER_COUNTRY_OPTIONS}
                icon={GlobeAltIcon}
                placeholder=""
                required
                error={errors.country}
              />
              <Select
                label={getRegionLabel(country)}
                name="region"
                value={region}
                onChange={(value) => setRegion(value)}
                options={getRegionOptions(country)}
                icon={MapPinIcon}
                placeholder={`Select ${getRegionLabel(country)}`}
                required
                error={errors.region}
              />
            </FormRow>

            <FormRow columns={2}>
              <Input
                label="City"
                name="city"
                value={city}
                onChange={(value) => setCity(value)}
                placeholder="Enter city"
                required
                error={errors.city}
              />
              <Input
                label={country === CUSTOMER_COUNTRIES.US ? "ZIP Code" : "Postal Code"}
                name="postalCode"
                value={postalCode}
                onChange={(value) => setPostalCode(value)}
                placeholder={
                  country === CUSTOMER_COUNTRIES.US
                    ? "Enter ZIP code"
                    : "Enter postal code"
                }
                required
                error={errors.postalCode}
              />
            </FormRow>

            <FormRow columns={1}>
              <Input
                label="Address Line 1"
                name="addressLine1"
                value={addressLine1}
                onChange={(value) => setAddressLine1(value)}
                placeholder="Enter street address"
                required
                error={errors.addressLine1}
              />
            </FormRow>

            <FormRow columns={1}>
              <Input
                label="Address Line 2 (Optional)"
                name="addressLine2"
                value={addressLine2}
                onChange={(value) => setAddressLine2(value)}
                placeholder="Apartment, suite, etc."
              />
            </FormRow>
          </FormSection>
        </FormCard>

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

        {/* Shipping/Billing Address Section */}
        {hasShippingAddress && (
          <FormCard
            title="Billing Address"
            icon={TruckIcon}
            description="Customer Billing Address"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={2}>
                <Input
                  label="Name (Optional)"
                  name="shippingName"
                  value={shippingName}
                  onChange={(value) => setShippingName(value)}
                  placeholder="Contact name for shipping"
                  icon={UserIcon}
                  error={errors.shippingName}
                />
                <Input
                  label="Phone (Optional)"
                  name="shippingPhone"
                  type="tel"
                  value={shippingPhone}
                  onChange={(value) => setShippingPhone(value)}
                  placeholder="Contact phone for shipping"
                  icon={PhoneIcon}
                  error={errors.shippingPhone}
                />
              </FormRow>

              <FormRow columns={2}>
                <Select
                  label="Country"
                  name="shippingCountry"
                  value={shippingCountry}
                  onChange={(value) => {
                    const regionOptions = getRegionOptions(value);
                    setShippingCountry(value);
                    if (regionOptions.length > 0) {
                      setShippingRegion(regionOptions[0].value);
                    }
                  }}
                  options={CUSTOMER_COUNTRY_OPTIONS}
                  icon={GlobeAltIcon}
                  placeholder=""
                  required
                  error={errors.shippingCountry}
                />
                <Select
                  label={getRegionLabel(shippingCountry)}
                  name="shippingRegion"
                  value={shippingRegion}
                  onChange={(value) => setShippingRegion(value)}
                  options={getRegionOptions(shippingCountry)}
                  icon={MapPinIcon}
                  placeholder={`Select ${getRegionLabel(shippingCountry)}`}
                  required
                  error={errors.shippingRegion}
                />
              </FormRow>

              <FormRow columns={2}>
                <Input
                  label="City"
                  name="shippingCity"
                  value={shippingCity}
                  onChange={(value) => setShippingCity(value)}
                  placeholder="Enter shipping city"
                  required
                  error={errors.shippingCity}
                />
                <Input
                  label={shippingCountry === CUSTOMER_COUNTRIES.US ? "ZIP Code" : "Postal Code"}
                  name="shippingPostalCode"
                  value={shippingPostalCode}
                  onChange={(value) => setShippingPostalCode(value)}
                  placeholder={
                    shippingCountry === CUSTOMER_COUNTRIES.US
                      ? "Enter ZIP code"
                      : "Enter postal code"
                  }
                  required
                  error={errors.shippingPostalCode}
                />
              </FormRow>

              <FormRow columns={1}>
                <Input
                  label="Address Line 1"
                  name="shippingAddressLine1"
                  value={shippingAddressLine1}
                  onChange={(value) => setShippingAddressLine1(value)}
                  placeholder="Enter shipping street address"
                  required
                  error={errors.shippingAddressLine1}
                />
              </FormRow>

              <FormRow columns={1}>
                <Input
                  label="Address Line 2 (Optional)"
                  name="shippingAddressLine2"
                  value={shippingAddressLine2}
                  onChange={(value) => setShippingAddressLine2(value)}
                  placeholder="Apartment, suite, etc."
                />
              </FormRow>
            </FormSection>
          </FormCard>
        )}

        {/* Form Actions */}
        <div className="flex flex-col sm:flex-row gap-3 mt-6">
          <Button
            type="button"
            variant="outline"
            onClick={handleBack}
            icon={ArrowLeftIcon}
            className="flex-1"
          >
            Back
          </Button>
          <Button
            type="submit"
            variant="primary"
            icon={ArrowRightIcon}
            disabled={isLoading}
            loading={isLoading}
            className="flex-1"
          >
            Next
          </Button>
        </div>
      </form>
    </StepWizard>
    </UIXThemeProvider>
  );
}

export default AdminCustomerAddStep4Page;
