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

import React, { useState, useEffect, useCallback, useMemo, memo } from "react";
import { useNavigate } from "react-router";
import { useStaffAddWizardStorage } from "../../../../services/Services";
import {
  UserPlusIcon,
  HomeIcon,
  TruckIcon,
  PhoneIcon,
  ArrowRightIcon,
} from "@heroicons/react/24/outline";
import {
  StaffWizardFormStep,
  AddressFormStep,
  UIXThemeProvider,
} from "../../../../components/UIX";
import Button from "../../../../components/UIX/Button/Button";

// Memoized content component
const Step4Content = memo(function Step4Content() {
  const navigate = useNavigate();
  const wizardStorage = useStaffAddWizardStorage();

  // PERFORMANCE: Memoize wizardState to prevent unnecessary re-computation
  const wizardState = useMemo(() => wizardStorage.getWizardState(), [wizardStorage]);

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

  // Address form data
  const [postalCode, setPostalCode] = useState(wizardState.postalCode || "");
  const [addressLine1, setAddressLine1] = useState(
    wizardState.addressLine1 || "",
  );
  const [addressLine2, setAddressLine2] = useState(
    wizardState.addressLine2 || "",
  );
  const [city, setCity] = useState(wizardState.city || "");
  const [region, setRegion] = useState(wizardState.region || "Ontario");
  const [country, setCountry] = useState(wizardState.country && wizardState.country.trim() !== "" ? wizardState.country : "Canada");
  const [hasShippingAddress, setHasShippingAddress] = useState(
    wizardState.hasShippingAddress || false,
  );

  // Shipping address data
  const [shippingName, setShippingName] = useState(
    wizardState.shippingName || "",
  );
  const [shippingPhone, setShippingPhone] = useState(
    wizardState.shippingPhone || "",
  );
  const [shippingCountry, setShippingCountry] = useState(
    wizardState.shippingCountry && wizardState.shippingCountry.trim() !== "" ? wizardState.shippingCountry : "Canada",
  );
  const [shippingRegion, setShippingRegion] = useState(
    wizardState.shippingRegion || "Ontario",
  );
  const [shippingCity, setShippingCity] = useState(
    wizardState.shippingCity || "",
  );
  const [shippingAddressLine1, setShippingAddressLine1] = useState(
    wizardState.shippingAddressLine1 || "",
  );
  const [shippingAddressLine2, setShippingAddressLine2] = useState(
    wizardState.shippingAddressLine2 || "",
  );
  const [shippingPostalCode, setShippingPostalCode] = useState(
    wizardState.shippingPostalCode || "",
  );

  // Scroll to top on mount only
  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);

  // Check for existing state and redirect if needed
  useEffect(() => {
    // If no wizard state exists, redirect back to step 1
    if (!wizardState || Object.keys(wizardState).length === 0) {
      navigate("/admin/staff/add/step-1-search");
    }
  }, [wizardState, navigate]);

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

    let newErrors = {};
    let hasErrors = false;

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

    // Shipping address validation (if enabled)
    if (hasShippingAddress) {
      if (!shippingName.trim()) {
        newErrors.shippingName = "Shipping name is required";
        hasErrors = true;
      }
      if (!shippingPhone.trim()) {
        newErrors.shippingPhone = "Shipping phone is required";
        hasErrors = true;
      }
      if (!shippingCountry.trim()) {
        newErrors.shippingCountry = "Shipping country is required";
        hasErrors = true;
      }
      if (!shippingRegion.trim()) {
        newErrors.shippingRegion = "Shipping province/territory 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 code is required";
        hasErrors = true;
      }
    }

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

    // Save to wizard storage
    wizardStorage.updateWizardState({
      postalCode,
      addressLine1,
      addressLine2,
      city,
      region,
      country,
      hasShippingAddress,
      shippingName,
      shippingPhone,
      shippingCountry,
      shippingRegion,
      shippingCity,
      shippingAddressLine1,
      shippingAddressLine2,
      shippingPostalCode,
    });

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

  // Memoized options to prevent re-renders
  const countryOptions = useMemo(() => [
    { value: "Canada", label: "Canada" },
    { value: "United States", label: "United States" },
    { value: "Mexico", label: "Mexico" },
  ], []);

  const regionOptions = useMemo(() => [
    { value: "Alberta", label: "Alberta" },
    { value: "British Columbia", label: "British Columbia" },
    { value: "Manitoba", label: "Manitoba" },
    { value: "New Brunswick", label: "New Brunswick" },
    { value: "Newfoundland and Labrador", label: "Newfoundland and Labrador" },
    { value: "Northwest Territories", label: "Northwest Territories" },
    { value: "Nova Scotia", label: "Nova Scotia" },
    { value: "Nunavut", label: "Nunavut" },
    { value: "Ontario", label: "Ontario" },
    { value: "Prince Edward Island", label: "Prince Edward Island" },
    { value: "Quebec", label: "Quebec" },
    { value: "Saskatchewan", label: "Saskatchewan" },
    { value: "Yukon", label: "Yukon" },
  ], []);

  // Wizard configuration
  const wizardSteps = useMemo(() => [
    { id: 1, title: "Search", subtitle: "Find Staff", isActive: false, isCompleted: true },
    { id: 2, title: "Type", subtitle: "Select Type", 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: "Account", subtitle: "Settings", isActive: false, isCompleted: false },
    { id: 6, title: "Metrics", subtitle: "Performance", isActive: false, isCompleted: false },
    { id: 7, title: "Comments", subtitle: "Notes", isActive: false, isCompleted: false },
  ], []);

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

  const handleCancel = useCallback(() => {
    navigate("/admin/staff");
  }, [navigate]);

  // Memoized input handlers to prevent re-rendering and focus issues
  // Note: UIX Input/Select components pass value directly, not event object
  const handleCountryChange = useCallback((value) => {
    setCountry(value);
  }, []);

  const handleRegionChange = useCallback((value) => {
    setRegion(value);
  }, []);

  const handleCityChange = useCallback((value) => {
    setCity(value);
  }, []);

  const handlePostalCodeChange = useCallback((value) => {
    setPostalCode(value);
  }, []);

  const handleAddressLine1Change = useCallback((value) => {
    setAddressLine1(value);
  }, []);

  const handleAddressLine2Change = useCallback((value) => {
    setAddressLine2(value);
  }, []);

  const handleHasShippingAddressChange = useCallback((checked) => {
    setHasShippingAddress(checked);
  }, []);

  // Shipping address handlers
  const handleShippingNameChange = useCallback((value) => {
    setShippingName(value);
  }, []);

  const handleShippingPhoneChange = useCallback((value) => {
    setShippingPhone(value);
  }, []);

  const handleShippingCountryChange = useCallback((value) => {
    setShippingCountry(value);
  }, []);

  const handleShippingRegionChange = useCallback((value) => {
    setShippingRegion(value);
  }, []);

  const handleShippingCityChange = useCallback((value) => {
    setShippingCity(value);
  }, []);

  const handleShippingPostalCodeChange = useCallback((value) => {
    setShippingPostalCode(value);
  }, []);

  const handleShippingAddressLine1Change = useCallback((value) => {
    setShippingAddressLine1(value);
  }, []);

  const handleShippingAddressLine2Change = useCallback((value) => {
    setShippingAddressLine2(value);
  }, []);

  // Action configuration
  const actions = useMemo(() => [
    {
      label: "Continue to Account Settings",
      variant: "primary",
      icon: ArrowRightIcon,
      onClick: onSubmitClick,
      disabled: isLoading,
    }
  ], [onSubmitClick, isLoading]);

  return (
    <StaffWizardFormStep
      wizardSteps={wizardSteps}
      currentStep={4}
      wizardTitle="Add New Staff Member"
      wizardIcon={UserPlusIcon}
      stepTitle="Address Information"
      stepSubtitle="Enter billing address and optional shipping address"
      stepIcon={HomeIcon}
      showFormCard={false}
      contentMaxWidth="7xl"
      errors={errors}
      isLoading={isLoading}
      actions={actions}
      onCancel={handleCancel}
      onBack={handleBack}
      actionLayout="end"
    >
      <AddressFormStep
        billingTitle={hasShippingAddress ? "Billing Address" : "Address Information"}
        billingSubtitle="Primary contact address for the staff member"
        billingIcon={HomeIcon}
        shippingTitle="Shipping Address"
        shippingSubtitle="Alternative address for deliveries and shipments"
        shippingIcon={TruckIcon}
        country={country}
        onCountryChange={handleCountryChange}
        region={region}
        onRegionChange={handleRegionChange}
        city={city}
        onCityChange={handleCityChange}
        postalCode={postalCode}
        onPostalCodeChange={handlePostalCodeChange}
        addressLine1={addressLine1}
        onAddressLine1Change={handleAddressLine1Change}
        addressLine2={addressLine2}
        onAddressLine2Change={handleAddressLine2Change}
        hasShippingAddress={hasShippingAddress}
        onHasShippingAddressChange={handleHasShippingAddressChange}
        shippingContactName={shippingName}
        onShippingContactNameChange={handleShippingNameChange}
        shippingPhone={shippingPhone}
        onShippingPhoneChange={handleShippingPhoneChange}
        shippingCountry={shippingCountry}
        onShippingCountryChange={handleShippingCountryChange}
        shippingRegion={shippingRegion}
        onShippingRegionChange={handleShippingRegionChange}
        shippingCity={shippingCity}
        onShippingCityChange={handleShippingCityChange}
        shippingPostalCode={shippingPostalCode}
        onShippingPostalCodeChange={handleShippingPostalCodeChange}
        shippingAddressLine1={shippingAddressLine1}
        onShippingAddressLine1Change={handleShippingAddressLine1Change}
        shippingAddressLine2={shippingAddressLine2}
        onShippingAddressLine2Change={handleShippingAddressLine2Change}
        countryOptions={countryOptions}
        regionOptions={regionOptions}
        errors={errors}
      />
    </StaffWizardFormStep>
  );
});

Step4Content.displayName = 'Step4Content';

function AdminStaffAddStep4Page() {
  return (
    <UIXThemeProvider>
      <Step4Content />
    </UIXThemeProvider>
  );
}

export default AdminStaffAddStep4Page;