'use client';

import { useEffect, useState } from 'react';
import {
  CustomerAddress,
  Country,
  Salutation,
  createAddress,
  updateAddress,
  getCustomerAddresses,
  setDefaultBillingAddress,
  setDefaultShippingAddress,
} from '@/lib/shopware-api';

type Mode = 'view' | 'edit' | 'create' | 'select';

interface AddressFormState {
  salutationId: string;
  firstName: string;
  lastName: string;
  company: string;
  department: string;
  street: string;
  additionalAddressLine1: string;
  zipcode: string;
  city: string;
  countryId: string;
}

const emptyForm: AddressFormState = {
  salutationId: '',
  firstName: '',
  lastName: '',
  company: '',
  department: '',
  street: '',
  additionalAddressLine1: '',
  zipcode: '',
  city: '',
  countryId: '',
};

interface AddressModalProps {
  open: boolean;
  type: 'shipping' | 'billing';
  currentAddress: CustomerAddress | null;
  salutations: Salutation[];
  countries: Country[];
  onClose: () => void;
  onSaved: () => void | Promise<void>;
}

export default function AddressModal({
  open,
  type,
  currentAddress,
  salutations,
  countries,
  onClose,
  onSaved,
}: AddressModalProps) {
  const [mode, setMode] = useState<Mode>('view');
  const [form, setForm] = useState<AddressFormState>(emptyForm);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [allAddresses, setAllAddresses] = useState<CustomerAddress[]>([]);
  const [addressesLoading, setAddressesLoading] = useState(false);
  const [settingDefaultId, setSettingDefaultId] = useState<string | null>(null);

  useEffect(() => {
    if (open) {
      setMode('view');
      setError('');
    }
  }, [open, currentAddress?.id]);

  // Load full address list when modal opens (needed for the Select mode)
  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setAddressesLoading(true);
    getCustomerAddresses()
      .then((res) => {
        if (!cancelled) setAllAddresses(res.elements || []);
      })
      .catch(() => {
        if (!cancelled) setAllAddresses([]);
      })
      .finally(() => {
        if (!cancelled) setAddressesLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [open]);

  // Close on Escape
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  // Lock body scroll while open
  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);

  if (!open) return null;

  const title = type === 'shipping' ? 'Current shipping address' : 'Current billing address';

  const startEdit = () => {
    if (!currentAddress) return;
    setForm({
      salutationId: currentAddress.salutationId || salutations[0]?.id || '',
      firstName: currentAddress.firstName || '',
      lastName: currentAddress.lastName || '',
      company: currentAddress.company || '',
      department: currentAddress.department || '',
      street: currentAddress.street || '',
      additionalAddressLine1: currentAddress.additionalAddressLine1 || '',
      zipcode: currentAddress.zipcode || '',
      city: currentAddress.city || '',
      countryId: currentAddress.countryId || countries[0]?.id || '',
    });
    setError('');
    setMode('edit');
  };

  const startCreate = () => {
    setForm({
      ...emptyForm,
      salutationId: salutations[0]?.id || '',
      countryId: countries[0]?.id || '',
    });
    setError('');
    setMode('create');
  };

  const handleUseAsDefault = async (addressId: string) => {
    setSettingDefaultId(addressId);
    setError('');
    try {
      if (type === 'shipping') {
        await setDefaultShippingAddress(addressId);
      } else {
        await setDefaultBillingAddress(addressId);
      }
      await onSaved();
      onClose();
    } catch (err: any) {
      setError(err.message || 'Failed to set default address.');
    } finally {
      setSettingDefaultId(null);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError('');
    try {
      const payload = {
        salutationId: form.salutationId || undefined,
        firstName: form.firstName,
        lastName: form.lastName,
        company: form.company || undefined,
        department: form.department || undefined,
        street: form.street,
        additionalAddressLine1: form.additionalAddressLine1 || undefined,
        zipcode: form.zipcode,
        city: form.city,
        countryId: form.countryId,
      };

      if (mode === 'edit' && currentAddress) {
        await updateAddress(currentAddress.id, payload as any);
      } else {
        const created = await createAddress(payload as any);
        // Make the new address the active one for this slot
        if (type === 'shipping') {
          await setDefaultShippingAddress(created.id);
        } else {
          await setDefaultBillingAddress(created.id);
        }
      }

      await onSaved();
      onClose();
    } catch (err: any) {
      setError(err.message || 'Failed to save address.');
    } finally {
      setSubmitting(false);
    }
  };

  const inputClass =
    'w-full border border-surface-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400 focus:border-brand-400';
  const labelClass = 'block text-sm text-surface-700 mb-1';

  return (
    <div
      className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/40 px-4 py-10"
      onClick={onClose}
    >
      <div
        className="relative w-full max-w-2xl bg-white rounded-xl shadow-xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-surface-100">
          <h3 className="font-semibold text-surface-900">{title}</h3>
          <button
            type="button"
            onClick={onClose}
            aria-label="Close"
            className="text-surface-400 hover:text-surface-700"
          >
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="px-6 py-5">
          {/* Current address summary */}
          {currentAddress ? (
            <div className="text-sm text-surface-700 space-y-0.5 mb-4">
              <p>
                {currentAddress.firstName} {currentAddress.lastName}
              </p>
              {currentAddress.company && <p>{currentAddress.company}</p>}
              <p>{currentAddress.street}</p>
              {currentAddress.additionalAddressLine1 && (
                <p>{currentAddress.additionalAddressLine1}</p>
              )}
              <p>
                {currentAddress.zipcode} {currentAddress.city}
              </p>
              <p>{currentAddress.country?.translated?.name || currentAddress.country?.name}</p>
            </div>
          ) : (
            <p className="text-sm text-surface-500 mb-4">
              No {type} address on file.
            </p>
          )}

          {/* Action buttons */}
          <div className="flex flex-wrap gap-3 mb-2">
            <button
              type="button"
              onClick={startEdit}
              disabled={!currentAddress}
              className={`px-4 py-2 text-sm font-semibold rounded-lg border border-brand-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
                mode === 'edit'
                  ? 'bg-brand-500 text-white'
                  : 'text-brand-600 hover:bg-brand-50'
              }`}
            >
              Edit address
            </button>
            {allAddresses.filter((a) => a.id !== currentAddress?.id).length > 0 && (
              <button
                type="button"
                onClick={() => {
                  setError('');
                  setMode('select');
                }}
                className={`px-4 py-2 text-sm font-semibold rounded-lg border border-brand-500 transition-colors ${
                  mode === 'select'
                    ? 'bg-brand-500 text-white'
                    : 'text-brand-600 hover:bg-brand-50'
                }`}
              >
                Select address
              </button>
            )}
            <button
              type="button"
              onClick={startCreate}
              className={`px-4 py-2 text-sm font-semibold rounded-lg border border-brand-500 transition-colors ${
                mode === 'create'
                  ? 'bg-brand-500 text-white'
                  : 'text-brand-600 hover:bg-brand-50'
              }`}
            >
              Add new address
            </button>
          </div>

          {/* Select address list */}
          {mode === 'select' && (
            <div className="mt-6 border-t border-surface-100 pt-6">
              <h4 className="font-semibold text-surface-900 border-b border-surface-100 pb-2 mb-4">
                Available addresses
              </h4>

              {error && (
                <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
                  {error}
                </div>
              )}

              {addressesLoading ? (
                <p className="text-sm text-surface-500">Loading addresses…</p>
              ) : (
                (() => {
                  const others = allAddresses.filter((a) => a.id !== currentAddress?.id);
                  if (others.length === 0) {
                    return (
                      <p className="text-sm text-surface-500">
                        No other saved addresses. Use “Add new address” to create one.
                      </p>
                    );
                  }
                  return (
                    <div className="space-y-6">
                      {others.map((addr) => (
                        <div key={addr.id} className="text-sm text-surface-700">
                          <div className="space-y-0.5 mb-3">
                            <p>
                              {addr.firstName} {addr.lastName}
                              {addr.company ? ` - ${addr.company}` : ''}
                            </p>
                            <p>{addr.street}</p>
                            {addr.additionalAddressLine1 && <p>{addr.additionalAddressLine1}</p>}
                            <p>
                              {addr.zipcode} {addr.city}
                            </p>
                            <p>{addr.country?.translated?.name || addr.country?.name}</p>
                          </div>
                          <button
                            type="button"
                            onClick={() => handleUseAsDefault(addr.id)}
                            disabled={settingDefaultId !== null}
                            className="px-4 py-2 text-sm font-semibold border border-surface-300 hover:border-surface-400 text-surface-800 rounded-lg transition-colors disabled:opacity-50"
                          >
                            {settingDefaultId === addr.id
                              ? 'Saving…'
                              : `Use as default ${type} address`}
                          </button>
                        </div>
                      ))}
                    </div>
                  );
                })()
              )}
            </div>
          )}

          {/* Form */}
          {(mode === 'edit' || mode === 'create') && (
            <form onSubmit={handleSubmit} className="mt-6 border-t border-surface-100 pt-6">
              <h4 className="font-semibold text-surface-900 mb-4">
                {mode === 'edit' ? 'Edit address' : 'New address'}
              </h4>

              {error && (
                <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
                  {error}
                </div>
              )}

              <div className="space-y-4">
                {/* Salutation */}
                <div>
                  <label className={labelClass}>Salutation</label>
                  <select
                    value={form.salutationId}
                    onChange={(e) => setForm((p) => ({ ...p, salutationId: e.target.value }))}
                    className={`${inputClass} max-w-[220px]`}
                  >
                    {salutations.map((s) => (
                      <option key={s.id} value={s.id}>
                        {s.translated?.displayName || s.displayName}
                      </option>
                    ))}
                  </select>
                </div>

                {/* First / Last name */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className={labelClass}>First name*</label>
                    <input
                      type="text"
                      required
                      value={form.firstName}
                      onChange={(e) => setForm((p) => ({ ...p, firstName: e.target.value }))}
                      className={inputClass}
                    />
                  </div>
                  <div>
                    <label className={labelClass}>Last name*</label>
                    <input
                      type="text"
                      required
                      value={form.lastName}
                      onChange={(e) => setForm((p) => ({ ...p, lastName: e.target.value }))}
                      className={inputClass}
                    />
                  </div>
                </div>

                {/* Company / Department */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className={labelClass}>Company</label>
                    <input
                      type="text"
                      value={form.company}
                      onChange={(e) => setForm((p) => ({ ...p, company: e.target.value }))}
                      className={inputClass}
                      placeholder="Enter company..."
                    />
                  </div>
                  <div>
                    <label className={labelClass}>Department</label>
                    <input
                      type="text"
                      value={form.department}
                      onChange={(e) => setForm((p) => ({ ...p, department: e.target.value }))}
                      className={inputClass}
                      placeholder="Enter department..."
                    />
                  </div>
                </div>

                {/* Street / Zip / City */}
                <div className="grid grid-cols-1 sm:grid-cols-6 gap-4">
                  <div className="col-span-3">
                    <label className={labelClass}>Street address*</label>
                    <input
                      type="text"
                      required
                      value={form.street}
                      onChange={(e) => setForm((p) => ({ ...p, street: e.target.value }))}
                      className={inputClass}
                    />
                  </div>
                  <div className="col-span-1">
                    <label className={labelClass}>Postal code*</label>
                    <input
                      type="text"
                      required
                      value={form.zipcode}
                      onChange={(e) => setForm((p) => ({ ...p, zipcode: e.target.value }))}
                      className={inputClass}
                    />
                  </div>
                  <div className="col-span-2">
                    <label className={labelClass}>City*</label>
                    <input
                      type="text"
                      required
                      value={form.city}
                      onChange={(e) => setForm((p) => ({ ...p, city: e.target.value }))}
                      className={inputClass}
                    />
                  </div>
                </div>

                {/* Country */}
                <div>
                  <label className={labelClass}>Country*</label>
                  <select
                    required
                    value={form.countryId}
                    onChange={(e) => setForm((p) => ({ ...p, countryId: e.target.value }))}
                    className={`${inputClass} max-w-sm`}
                  >
                    <option value="">Select country...</option>
                    {countries.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.translated?.name || c.name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <p className="text-xs text-surface-500 mt-4">
                Fields marked with asterisks (*) are required.
              </p>

              <div className="flex gap-3 mt-5">
                <button
                  type="submit"
                  disabled={submitting}
                  className="px-5 py-2.5 bg-brand-500 hover:bg-brand-600 disabled:bg-brand-300 text-white text-sm font-semibold rounded-lg transition-colors"
                >
                  {submitting ? 'Saving...' : 'Save address'}
                </button>
                <button
                  type="button"
                  onClick={() => setMode('view')}
                  disabled={submitting}
                  className="px-5 py-2.5 border border-surface-200 hover:border-surface-300 text-surface-700 text-sm font-semibold rounded-lg transition-colors"
                >
                  Cancel
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
