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

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

// Constants - moved outside component
const WIZARD_STEPS = [
  { title: "Search", isCompleted: true },
  { title: "Type", isCompleted: true },
  { title: "Contact", isCompleted: true },
  { title: "Address", isCompleted: false },
  { title: "Account" },
  { title: "Metrics" },
  { title: "Review" },
];

const COUNTRY_OPTIONS = [
  { value: "Canada", label: "Canada" },
  { value: "United States", label: "United States" },
  { value: "Mexico", label: "Mexico" },
];

const REGION_OPTIONS = [
  { 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" },
];

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

  // 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("Ontario");
  const [country, setCountry] = useState("Canada");
  const [hasShippingAddress, setHasShippingAddress] = useState(false);

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

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

    loadSpeakerState();
  }, [authManager, navigate]);

  const loadSpeakerState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem(
        "FLASHPOINTTRAINING_SPEAKER_CREATION_STATE",
      );
      if (existing) {
        const speakerState = JSON.parse(existing);

        // Load billing address
        setPostalCode(speakerState.postalCode || "");
        setAddressLine1(speakerState.addressLine1 || "");
        setAddressLine2(speakerState.addressLine2 || "");
        setCity(speakerState.city || "");
        setRegion(speakerState.region || "Ontario");
        setCountry(speakerState.country || "Canada");
        setHasShippingAddress(speakerState.hasShippingAddress || false);

        // Load shipping address
        setShippingName(speakerState.shippingName || "");
        setShippingPhone(speakerState.shippingPhone || "");
        setShippingCountry(speakerState.shippingCountry || "Canada");
        setShippingRegion(speakerState.shippingRegion || "Ontario");
        setShippingCity(speakerState.shippingCity || "");
        setShippingAddressLine1(speakerState.shippingAddressLine1 || "");
        setShippingAddressLine2(speakerState.shippingAddressLine2 || "");
        setShippingPostalCode(speakerState.shippingPostalCode || "");
      } else {
        // No state found, redirect back to step 1
        navigate("/admin/speakers/add/step-1-search");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error loading speaker state:", error);
      }
      navigate("/admin/speakers/add/step-1-search");
    }
  }, [navigate]);

  const getExistingState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem(
        "FLASHPOINTTRAINING_SPEAKER_CREATION_STATE",
      );
      return existing ? JSON.parse(existing) : {};
    } catch (error) {
      return {};
    }
  }, []);

  const copyBillingToShipping = useCallback(() => {
    const existingState = getExistingState();
    const fullName =
      `${existingState.firstName || ""} ${existingState.lastName || ""}`.trim();

    setShippingName(fullName);
    setShippingPhone(existingState.phone || "");
    setShippingCountry(country);
    setShippingRegion(region);
    setShippingCity(city);
    setShippingAddressLine1(addressLine1);
    setShippingAddressLine2(addressLine2);
    setShippingPostalCode(postalCode);
  }, [getExistingState, country, region, city, addressLine1, addressLine2, postalCode]);

  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);
      return;
    }

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

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

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

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={4}
        title="Add New Speaker"
        subtitle="Enter address information for the new speaker"
        icon={ChatBubbleBottomCenterIcon}
      >
        <form onSubmit={onSubmitClick}>
          {/* Error Alert */}
          {errors.general && (
            <Alert
              type="error"
              message={errors.general}
              onClose={() => setErrors({})}
              className="mb-6"
            />
          )}

          {/* Billing Address Section */}
          <FormCard
            title={hasShippingAddress ? "Billing Address" : "Address Information"}
            icon={hasShippingAddress ? BuildingOfficeIcon : HomeIcon}
            description={
              hasShippingAddress
                ? "Primary billing address for invoices"
                : "Primary address for the speaker"
            }
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={2}>
                <Select
                  label="Country"
                  name="country"
                  value={country}
                  onChange={(value) => setCountry(value)}
                  options={COUNTRY_OPTIONS}
                  icon={GlobeAltIcon}
                  placeholder=""
                  required
                  error={errors.country}
                />
                <Select
                  label="Province/Territory"
                  name="region"
                  value={region}
                  onChange={(value) => setRegion(value)}
                  options={REGION_OPTIONS}
                  icon={MapPinIcon}
                  placeholder=""
                  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="Postal Code"
                  name="postalCode"
                  value={postalCode}
                  onChange={(value) => setPostalCode(value)}
                  placeholder="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, unit, building, floor, etc."
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Shipping Address Toggle */}
          <div className="mb-6">
            <div className="flex items-center justify-between">
              <Checkbox
                id="hasShippingAddress"
                label="Different shipping address"
                checked={hasShippingAddress}
                onChange={(checked) => setHasShippingAddress(checked)}
              />
              {hasShippingAddress && (
                <Button
                  type="button"
                  variant="ghost"
                  onClick={copyBillingToShipping}
                  size="sm"
                >
                  Copy from billing
                </Button>
              )}
            </div>
            <p className="mt-2 text-sm opacity-60 ml-6">
              Check this if materials should be shipped to a different address
            </p>
          </div>

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

                <FormRow columns={2}>
                  <Select
                    label="Country"
                    name="shippingCountry"
                    value={shippingCountry}
                    onChange={(value) => setShippingCountry(value)}
                    options={COUNTRY_OPTIONS}
                    icon={GlobeAltIcon}
                    placeholder=""
                    required
                    error={errors.shippingCountry}
                  />
                  <Select
                    label="Province/Territory"
                    name="shippingRegion"
                    value={shippingRegion}
                    onChange={(value) => setShippingRegion(value)}
                    options={REGION_OPTIONS}
                    icon={MapPinIcon}
                    placeholder=""
                    required
                    error={errors.shippingRegion}
                  />
                </FormRow>

                <FormRow columns={2}>
                  <Input
                    label="City"
                    name="shippingCity"
                    value={shippingCity}
                    onChange={(value) => setShippingCity(value)}
                    placeholder="Enter city"
                    required
                    error={errors.shippingCity}
                  />
                  <Input
                    label="Postal Code"
                    name="shippingPostalCode"
                    value={shippingPostalCode}
                    onChange={(value) => setShippingPostalCode(value)}
                    placeholder="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 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, unit, building, floor, 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 AdminSpeakerAddStep4Page;
