'use client';

/**
 * ============================================
 * MANAGE ADDRESSES PAGE
 * ============================================
 * Equivalent to: account/address/index.html.twig in Shopware
 * Add, edit, delete addresses; set billing/shipping defaults
 */

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import AccountNav from '@/components/layout/AccountNav';
import {
  getCustomerAddresses,
  createAddress,
  updateAddress,
  deleteAddress,
  setDefaultBillingAddress,
  setDefaultShippingAddress,
  getCountries,
  getSalutations,
  CustomerAddress,
  Country,
  Salutation,
} from '@/lib/shopware-api';

type AddressFormData = {
  salutationId: string;
  firstName: string;
  lastName: string;
  street: string;
  additionalAddressLine1: string;
  zipcode: string;
  city: string;
  countryId: string;
};

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

export default function AddressesPage() {
  const { customer, isLoggedIn, isLoading, refreshCustomer } = useAuth();
  const router = useRouter();

  const [addresses, setAddresses] = useState<CustomerAddress[]>([]);
  const [countries, setCountries] = useState<Country[]>([]);
  const [salutations, setSalutations] = useState<Salutation[]>([]);
  const [pageLoading, setPageLoading] = useState(true);

  // Form state
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<AddressFormData>(emptyForm);
  const [formError, setFormError] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const [actionError, setActionError] = useState('');

  useEffect(() => {
    if (!isLoading && !isLoggedIn) router.push('/account/login');
  }, [isLoading, isLoggedIn, router]);

  const loadData = useCallback(async () => {
    if (!isLoggedIn) return;
    try {
      // Load countries and salutations independently so a failure in one doesn't block others
      const [addrResult, countryResult, salutationResult] = await Promise.allSettled([
        getCustomerAddresses(),
        getCountries(),
        getSalutations(),
      ]);
      if (addrResult.status === 'fulfilled') setAddresses(addrResult.value.elements || []);
      if (countryResult.status === 'fulfilled') setCountries(countryResult.value.elements || []);
      if (salutationResult.status === 'fulfilled') setSalutations(salutationResult.value.elements || []);
    } catch (e) {
      console.error('Failed to load addresses:', e);
    } finally {
      setPageLoading(false);
    }
  }, [isLoggedIn]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  const openAddForm = () => {
    setEditingId(null);
    setForm({ ...emptyForm, firstName: customer?.firstName || '', lastName: customer?.lastName || '' });
    setFormError('');
    setShowForm(true);
    setTimeout(() => document.getElementById('addr-form')?.scrollIntoView({ behavior: 'smooth' }), 50);
  };

  const openEditForm = (addr: CustomerAddress) => {
    setEditingId(addr.id);
    setForm({
      salutationId: addr.salutationId || '',
      firstName: addr.firstName,
      lastName: addr.lastName,
      street: addr.street,
      additionalAddressLine1: addr.additionalAddressLine1 || '',
      zipcode: addr.zipcode,
      city: addr.city,
      countryId: addr.countryId,
    });
    setFormError('');
    setShowForm(true);
    setTimeout(() => document.getElementById('addr-form')?.scrollIntoView({ behavior: 'smooth' }), 50);
  };

  const cancelForm = () => {
    setShowForm(false);
    setEditingId(null);
    setForm(emptyForm);
    setFormError('');
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError('');
    setSubmitting(true);
    try {
      const payload = {
        salutationId: form.salutationId || undefined,
        firstName: form.firstName,
        lastName: form.lastName,
        street: form.street,
        additionalAddressLine1: form.additionalAddressLine1 || undefined,
        zipcode: form.zipcode,
        city: form.city,
        countryId: form.countryId,
      };
      if (editingId) {
        await updateAddress(editingId, payload as any);
      } else {
        await createAddress(payload as any);
      }
      await loadData();
      cancelForm();
    } catch (err: any) {
      setFormError(err.message || 'Failed to save address.');
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this address?')) return;
    setActionError('');
    try {
      await deleteAddress(id);
      setAddresses((prev) => prev.filter((a) => a.id !== id));
    } catch (err: any) {
      setActionError(err.message || 'Could not delete address.');
    }
  };

  const handleSetDefault = async (id: string, type: 'billing' | 'shipping') => {
    setActionError('');
    try {
      if (type === 'billing') await setDefaultBillingAddress(id);
      else await setDefaultShippingAddress(id);
      await refreshCustomer();
    } catch (err: any) {
      setActionError(err.message || 'Could not set default address.');
    }
  };

  if (isLoading || pageLoading) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <svg className="w-6 h-6 animate-spin text-surface-400" viewBox="0 0 24 24" fill="none">
          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
        </svg>
      </div>
    );
  }

  const inputClass = 'w-full px-4 py-3 rounded-xl border border-surface-200 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 outline-none transition-all text-surface-900';

  return (
    <div className="max-w-5xl mx-auto px-6 py-10">
      <div className="grid md:grid-cols-[220px_1fr] gap-8">
        <AccountNav />

        <div>
          <div className="flex items-center justify-between mb-6">
            <h1 className="text-2xl font-bold text-surface-900">My Addresses</h1>
            {!showForm && (
              <button
                onClick={openAddForm}
                className="flex items-center gap-2 px-4 py-2 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-xl transition-colors"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                </svg>
                Add Address
              </button>
            )}
          </div>

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

          {/* Address Form */}
          {showForm && (
            <div id="addr-form" className="bg-white border border-surface-200 rounded-2xl p-6 mb-6">
              <h2 className="text-lg font-semibold mb-5">{editingId ? 'Edit Address' : 'New Address'}</h2>
              {formError && (
                <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700">{formError}</div>
              )}
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Salutation</label>
                  <select value={form.salutationId} onChange={(e) => setForm((p) => ({ ...p, salutationId: e.target.value }))} className={inputClass}>
                    <option value="">Select...</option>
                    {salutations.map((s) => (
                      <option key={s.id} value={s.id}>{s.translated?.displayName || s.displayName}</option>
                    ))}
                  </select>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-surface-700 mb-1.5">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="block text-sm font-medium text-surface-700 mb-1.5">Last Name *</label>
                    <input type="text" required value={form.lastName} onChange={(e) => setForm((p) => ({ ...p, lastName: e.target.value }))} className={inputClass} />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Street Address *</label>
                  <input type="text" required value={form.street} onChange={(e) => setForm((p) => ({ ...p, street: e.target.value }))} className={inputClass} placeholder="123 Main Street" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Additional Address Line</label>
                  <input type="text" value={form.additionalAddressLine1} onChange={(e) => setForm((p) => ({ ...p, additionalAddressLine1: e.target.value }))} className={inputClass} placeholder="Apt, suite, floor..." />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-surface-700 mb-1.5">Postal Code *</label>
                    <input type="text" required value={form.zipcode} onChange={(e) => setForm((p) => ({ ...p, zipcode: e.target.value }))} className={inputClass} />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-surface-700 mb-1.5">City *</label>
                    <input type="text" required value={form.city} onChange={(e) => setForm((p) => ({ ...p, city: e.target.value }))} className={inputClass} />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-surface-700 mb-1.5">Country *</label>
                  <select required value={form.countryId} onChange={(e) => setForm((p) => ({ ...p, countryId: e.target.value }))} className={inputClass}>
                    <option value="">Select country...</option>
                    {countries.map((c) => (
                      <option key={c.id} value={c.id}>{c.translated?.name || c.name}</option>
                    ))}
                  </select>
                </div>
                <div className="flex gap-3 pt-2">
                  <button type="submit" disabled={submitting} className="px-6 py-3 bg-brand-500 hover:bg-brand-600 disabled:bg-brand-300 text-white font-semibold rounded-xl transition-colors">
                    {submitting ? 'Saving...' : editingId ? 'Update Address' : 'Save Address'}
                  </button>
                  <button type="button" onClick={cancelForm} className="px-6 py-3 border border-surface-200 hover:border-surface-400 text-surface-600 font-semibold rounded-xl transition-colors">
                    Cancel
                  </button>
                </div>
              </form>
            </div>
          )}

          {/* Address list */}
          {addresses.length === 0 && !showForm ? (
            <div className="text-center py-16 bg-surface-50 rounded-2xl">
              <span className="text-4xl mb-3 block">📍</span>
              <p className="text-surface-500 mb-4">No addresses saved yet.</p>
              <button onClick={openAddForm} className="px-6 py-2.5 bg-brand-500 hover:bg-brand-600 text-white font-semibold rounded-xl transition-colors">
                Add Your First Address
              </button>
            </div>
          ) : (
            <div className="space-y-4">
              {addresses.map((addr) => {
                const isBilling = addr.id === customer?.defaultBillingAddressId;
                const isShipping = addr.id === customer?.defaultShippingAddressId;
                return (
                  <div key={addr.id} className="bg-white border border-surface-200 rounded-2xl p-5">
                    <div className="flex items-start justify-between gap-4">
                      <div className="text-sm text-surface-700 space-y-0.5">
                        <p className="font-semibold text-surface-900">{addr.firstName} {addr.lastName}</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>
                      <div className="flex flex-col items-end gap-2 shrink-0">
                        {/* Default badges */}
                        <div className="flex gap-2 flex-wrap justify-end">
                          {isBilling && (
                            <span className="text-xs font-medium px-2.5 py-1 bg-brand-100 text-brand-700 rounded-full">Billing</span>
                          )}
                          {isShipping && (
                            <span className="text-xs font-medium px-2.5 py-1 bg-green-100 text-green-700 rounded-full">Shipping</span>
                          )}
                        </div>
                        {/* Actions */}
                        <div className="flex gap-2">
                          <button onClick={() => openEditForm(addr)} className="text-xs font-medium text-surface-500 hover:text-surface-900 border border-surface-200 hover:border-surface-400 px-3 py-1.5 rounded-lg transition-colors">
                            Edit
                          </button>
                          {!isBilling && !isShipping && (
                            <button onClick={() => handleDelete(addr.id)} className="text-xs font-medium text-red-400 hover:text-red-600 border border-red-100 hover:border-red-300 px-3 py-1.5 rounded-lg transition-colors">
                              Delete
                            </button>
                          )}
                        </div>
                      </div>
                    </div>
                    {/* Set as default buttons */}
                    <div className="flex gap-2 mt-4 pt-4 border-t border-surface-100">
                      {!isBilling && (
                        <button onClick={() => handleSetDefault(addr.id, 'billing')} className="text-xs text-surface-500 hover:text-brand-600 transition-colors">
                          Set as billing default
                        </button>
                      )}
                      {!isBilling && !isShipping && <span className="text-surface-200 text-xs">|</span>}
                      {!isShipping && (
                        <button onClick={() => handleSetDefault(addr.id, 'shipping')} className="text-xs text-surface-500 hover:text-brand-600 transition-colors">
                          Set as shipping default
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
