'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';

interface Profile {
  id: string;
  email: string;
  displayName: string | null;
  phone: string | null;
}

interface Preferences {
  orderUpdates: boolean;
  newsletter: boolean;
  promos: boolean;
}

const DEFAULT_PREFS: Preferences = { orderUpdates: true, newsletter: false, promos: false };

const PREF_ITEMS: Array<{ key: keyof Preferences; title: string; desc: string }> = [
  { key: 'orderUpdates', title: 'Estado de mis pedidos', desc: 'Recibe un email cuando tu pedido cambie de estado (pagado, enviado, entregado...).' },
  { key: 'newsletter', title: 'Boletín de novedades', desc: 'Nuevos productos, recetas y consejos de vida saludable.' },
  { key: 'promos', title: 'Ofertas y promociones', desc: 'Avisos de descuentos y promociones especiales.' },
];

interface Address {
  id: string;
  userId: string;
  label: string | null;
  recipientName: string;
  street: string;
  city: string;
  postalCode: string;
  country: string;
  isDefault: boolean;
  createdAt: string;
  updatedAt: string;
}

const emptyForm = {
  label: '',
  recipientName: '',
  street: '',
  city: '',
  postalCode: '',
  country: 'España',
  isDefault: false,
};

function AddressForm({
  initial,
  userId,
  onSaved,
  onCancel,
}: {
  initial?: Address;
  userId: string;
  onSaved: () => void;
  onCancel: () => void;
}) {
  const [form, setForm] = useState(initial ? {
    label: initial.label ?? '',
    recipientName: initial.recipientName,
    street: initial.street,
    city: initial.city,
    postalCode: initial.postalCode,
    country: initial.country,
    isDefault: initial.isDefault,
  } : { ...emptyForm });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const set = (field: string, value: string | boolean) =>
    setForm((f) => ({ ...f, [field]: value }));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setError('');
    try {
      const url = initial
        ? `/api/users/${userId}/addresses/${initial.id}`
        : `/api/users/${userId}/addresses`;
      const method = initial ? 'PATCH' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          ...form,
          label: form.label || null,
        }),
      });
      if (!res.ok) throw new Error(`Error ${res.status}`);
      onSaved();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al guardar');
    } finally {
      setSaving(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-stone-700 mb-1">Etiqueta</label>
          <input
            type="text"
            value={form.label}
            onChange={(e) => set('label', e.target.value)}
            placeholder="Casa, Oficina..."
            className="w-full px-3 py-2 border border-stone-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-stone-700 mb-1">Destinatario *</label>
          <input
            type="text"
            value={form.recipientName}
            onChange={(e) => set('recipientName', e.target.value)}
            required
            className="w-full px-3 py-2 border border-stone-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
          />
        </div>
      </div>
      <div>
        <label className="block text-sm font-medium text-stone-700 mb-1">Dirección *</label>
        <input
          type="text"
          value={form.street}
          onChange={(e) => set('street', e.target.value)}
          required
          className="w-full px-3 py-2 border border-stone-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
        />
      </div>
      <div className="grid grid-cols-3 gap-4">
        <div>
          <label className="block text-sm font-medium text-stone-700 mb-1">Ciudad *</label>
          <input
            type="text"
            value={form.city}
            onChange={(e) => set('city', e.target.value)}
            required
            className="w-full px-3 py-2 border border-stone-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-stone-700 mb-1">Código postal *</label>
          <input
            type="text"
            value={form.postalCode}
            onChange={(e) => set('postalCode', e.target.value)}
            required
            className="w-full px-3 py-2 border border-stone-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-stone-700 mb-1">País *</label>
          <input
            type="text"
            value={form.country}
            onChange={(e) => set('country', e.target.value)}
            required
            className="w-full px-3 py-2 border border-stone-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
          />
        </div>
      </div>
      <label className="flex items-center gap-2 text-sm text-stone-700">
        <input
          type="checkbox"
          checked={form.isDefault}
          onChange={(e) => set('isDefault', e.target.checked)}
          className="rounded border-stone-300 text-[#2D6A4F] focus:ring-[#2D6A4F]"
        />
        Dirección predeterminada
      </label>
      {error && <p className="text-sm text-red-600 bg-red-50 rounded-lg px-3 py-2">{error}</p>}
      <div className="flex gap-3 pt-2">
        <button
          type="submit"
          disabled={saving}
          className="px-5 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] disabled:opacity-50 text-white text-sm font-semibold rounded-lg transition-colors"
        >
          {saving ? 'Guardando...' : initial ? 'Actualizar' : 'Añadir dirección'}
        </button>
        <button
          type="button"
          onClick={onCancel}
          className="px-5 py-2 border border-stone-300 text-stone-600 text-sm rounded-lg hover:bg-stone-50 transition-colors"
        >
          Cancelar
        </button>
      </div>
    </form>
  );
}

export default function AccountPage() {
  const { user, loading: authLoading } = useAuth();
  const router = useRouter();
  const [addresses, setAddresses] = useState<Address[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState<Address | null>(null);
  const [msg, setMsg] = useState('');
  const [profile, setProfile] = useState<Profile | null>(null);
  const [profileForm, setProfileForm] = useState({ displayName: '', phone: '' });
  const [profileSaving, setProfileSaving] = useState(false);
  const [profileError, setProfileError] = useState('');
  const [prefs, setPrefs] = useState<Preferences>(DEFAULT_PREFS);
  const [prefsMsg, setPrefsMsg] = useState('');
  const [passwordForm, setPasswordForm] = useState({ currentPassword: '', newPassword: '', confirmPassword: '' });
  const [passwordSaving, setPasswordSaving] = useState(false);
  const [passwordMessage, setPasswordMessage] = useState('');
  const [passwordError, setPasswordError] = useState('');

  useEffect(() => {
    if (!authLoading && !user) {
      router.push('/auth/login');
    }
  }, [user, authLoading, router]);

  const load = useCallback(async () => {
    if (!user) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/users/${user.id}/addresses`, { credentials: 'include' });
      if (res.ok) {
        const data = await res.json();
        setAddresses(data.items ?? []);
      }
    } catch {
      // silent
    } finally {
      setLoading(false);
    }
  }, [user]);

  useEffect(() => {
    if (!user) return;
    fetch(`/api/users/${user.id}`, { credentials: 'include' })
      .then((res) => res.ok ? res.json() : null)
      .then((data: Profile | null) => {
        if (!data) return;
        setProfile(data);
        setProfileForm({ displayName: data.displayName ?? '', phone: data.phone ?? '' });
        const p = (data as Profile & { preferences?: Partial<Preferences> }).preferences;
        if (p) setPrefs({ ...DEFAULT_PREFS, ...p });
      })
      .catch(() => setProfileError('No se pudieron cargar tus datos personales'));
  }, [user]);

  const saveProfile = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!user) return;
    setProfileSaving(true); setProfileError('');
    try {
      const res = await fetch(`/api/users/${user.id}`, {
        method: 'PATCH', headers: { 'Content-Type': 'application/json' }, credentials: 'include',
        body: JSON.stringify({ displayName: profileForm.displayName, phone: profileForm.phone }),
      });
      const data = await res.json().catch(() => null);
      if (!res.ok) throw new Error(data?.error?.message ?? 'No se pudieron guardar los datos');
      setProfile(data); setMsg('Datos personales actualizados');
    } catch (error) {
      setProfileError(error instanceof Error ? error.message : 'No se pudieron guardar los datos');
    } finally { setProfileSaving(false); }
  };

  const changePassword = async (event: React.FormEvent) => {
    event.preventDefault();
    setPasswordError(''); setPasswordMessage('');
    if (passwordForm.newPassword.length < 8) { setPasswordError('La nueva contraseña debe tener al menos 8 caracteres.'); return; }
    if (passwordForm.newPassword !== passwordForm.confirmPassword) { setPasswordError('Las contraseñas nuevas no coinciden.'); return; }
    setPasswordSaving(true);
    try {
      const res = await fetch('/api/auth/me/password', {
        method: 'PATCH', headers: { 'Content-Type': 'application/json' }, credentials: 'include',
        body: JSON.stringify({ currentPassword: passwordForm.currentPassword, newPassword: passwordForm.newPassword }),
      });
      const data = await res.json().catch(() => null);
      if (!res.ok) throw new Error(data?.error?.message ?? 'No se pudo cambiar la contraseña');
      setPasswordForm({ currentPassword: '', newPassword: '', confirmPassword: '' });
      setPasswordMessage('Contraseña actualizada correctamente');
    } catch (error) {
      setPasswordError(error instanceof Error ? error.message : 'No se pudo cambiar la contraseña');
    } finally { setPasswordSaving(false); }
  };

  const togglePref = async (key: keyof Preferences) => {
    if (!user) return;
    const value = !prefs[key];
    const prev = prefs;
    setPrefs((p) => ({ ...p, [key]: value }));
    setPrefsMsg('');
    try {
      const res = await fetch(`/api/users/${user.id}`, {
        method: 'PATCH', headers: { 'Content-Type': 'application/json' }, credentials: 'include',
        body: JSON.stringify({ preferences: { [key]: value } }),
      });
      if (!res.ok) throw new Error();
      setPrefsMsg('Preferencias actualizadas');
      setTimeout(() => setPrefsMsg(''), 3000);
    } catch {
      setPrefs(prev);
      setPrefsMsg('Error al guardar las preferencias');
    }
  };

  const handleDelete = async (id: string) => {
    if (!user || !confirm('¿Eliminar esta dirección?')) return;
    try {
      await fetch(`/api/users/${user.id}/addresses/${id}`, { method: 'DELETE', credentials: 'include' });
      setMsg('Dirección eliminada');
      setTimeout(() => setMsg(''), 3000);
      load();
    } catch {
      setMsg('Error al eliminar');
    }
  };

  if (authLoading || !user) {
    return <div className="max-w-4xl mx-auto px-4 py-12 text-stone-400">Cargando...</div>;
  }

  return (
    <div className="max-w-3xl mx-auto px-4 py-8 space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-stone-900">Mi cuenta</h1>
        <p className="text-sm text-stone-500 mt-1">{user.email}</p>
      </div>

      {msg && (
        <div className={`p-3 rounded-lg text-sm ${msg.includes('Error') ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green-700'}`}>
          {msg}
        </div>
      )}

      {/* Personal data */}
      <section className="rounded-xl border border-stone-200 bg-white p-5">
        <h2 className="mb-4 text-lg font-semibold text-stone-900">Datos personales</h2>
        <form onSubmit={saveProfile} className="grid gap-4 sm:grid-cols-2">
          <label className="text-sm font-medium text-stone-700">Nombre
            <input value={profileForm.displayName} onChange={(e) => setProfileForm(f => ({ ...f, displayName: e.target.value }))} required className="mt-1 w-full rounded-lg border border-stone-300 px-3 py-2 font-normal outline-none focus:ring-2 focus:ring-[#2D6A4F]" />
          </label>
          <label className="text-sm font-medium text-stone-700">Teléfono
            <input value={profileForm.phone} onChange={(e) => setProfileForm(f => ({ ...f, phone: e.target.value }))} className="mt-1 w-full rounded-lg border border-stone-300 px-3 py-2 font-normal outline-none focus:ring-2 focus:ring-[#2D6A4F]" />
          </label>
          {profileError && <p className="sm:col-span-2 text-sm text-red-600">{profileError}</p>}
          <button disabled={profileSaving} className="w-fit rounded-lg bg-[#2D6A4F] px-5 py-2 text-sm font-semibold text-white disabled:opacity-50">{profileSaving ? 'Guardando...' : 'Guardar datos'}</button>
        </form>
      </section>

      {/* Password */}
      <section className="rounded-xl border border-stone-200 bg-white p-5">
        <div className="mb-4 flex items-center justify-between gap-4">
          <h2 className="text-lg font-semibold text-stone-900">Contraseña</h2>
          <a href="/auth/recuperar" className="text-sm text-[#2D6A4F] hover:underline">¿Has olvidado tu contraseña?</a>
        </div>
        <form onSubmit={changePassword} className="max-w-xl space-y-4">
          <label className="block text-sm font-medium text-stone-700">Contraseña actual
            <input type="password" required value={passwordForm.currentPassword} onChange={(e) => setPasswordForm(f => ({ ...f, currentPassword: e.target.value }))} className="mt-1 w-full rounded-lg border border-stone-300 px-3 py-2 font-normal outline-none focus:ring-2 focus:ring-[#2D6A4F]" />
          </label>
          <div className="grid gap-4 sm:grid-cols-2">
            <label className="text-sm font-medium text-stone-700">Nueva contraseña
              <input type="password" minLength={8} required value={passwordForm.newPassword} onChange={(e) => setPasswordForm(f => ({ ...f, newPassword: e.target.value }))} className="mt-1 w-full rounded-lg border border-stone-300 px-3 py-2 font-normal outline-none focus:ring-2 focus:ring-[#2D6A4F]" />
            </label>
            <label className="text-sm font-medium text-stone-700">Repetir contraseña
              <input type="password" minLength={8} required value={passwordForm.confirmPassword} onChange={(e) => setPasswordForm(f => ({ ...f, confirmPassword: e.target.value }))} className="mt-1 w-full rounded-lg border border-stone-300 px-3 py-2 font-normal outline-none focus:ring-2 focus:ring-[#2D6A4F]" />
            </label>
          </div>
          {passwordError && <p className="text-sm text-red-600">{passwordError}</p>}
          {passwordMessage && <p className="text-sm text-green-700">{passwordMessage}</p>}
          <button disabled={passwordSaving} className="rounded-lg bg-[#2D6A4F] px-5 py-2 text-sm font-semibold text-white disabled:opacity-50">{passwordSaving ? 'Actualizando...' : 'Cambiar contraseña'}</button>
        </form>
      </section>

      {/* Preferences */}
      <section className="rounded-xl border border-stone-200 bg-white p-5">
        <h2 className="mb-1 text-lg font-semibold text-stone-900">Preferencias</h2>
        <p className="mb-4 text-sm text-stone-500">Elige qué comunicaciones quieres recibir por email.</p>
        {prefsMsg && (
          <p className={`mb-3 text-sm ${prefsMsg.startsWith('Error') ? 'text-red-600' : 'text-green-700'}`}>{prefsMsg}</p>
        )}
        <div className="divide-y divide-stone-100">
          {PREF_ITEMS.map((item) => (
            <div
              key={item.key}
              role="switch"
              aria-checked={prefs[item.key]}
              tabIndex={0}
              onClick={() => togglePref(item.key)}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); togglePref(item.key); } }}
              className="flex items-start justify-between gap-4 py-3 cursor-pointer select-none"
            >
              <span>
                <span className="block text-sm font-medium text-stone-800">{item.title}</span>
                <span className="block text-xs text-stone-500 mt-0.5">{item.desc}</span>
              </span>
              <span
                className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors ${
                  prefs[item.key] ? 'bg-[#2D6A4F]' : 'bg-stone-300'
                }`}
              >
                <span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                  prefs[item.key] ? 'translate-x-6' : 'translate-x-1'
                }`} />
              </span>
            </div>
          ))}
        </div>
      </section>

      {/* Addresses */}
      <section>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-stone-900">Direcciones</h2>
          <button
            onClick={() => { setShowForm(true); setEditing(null); }}
            className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] text-white text-sm font-semibold rounded-lg transition-colors"
          >
            + Nueva dirección
          </button>
        </div>

        {(showForm || editing) && (
          <div className="bg-white border border-stone-200 rounded-xl p-5 mb-4">
            <AddressForm
              initial={editing ?? undefined}
              userId={user.id}
              onSaved={() => {
                setShowForm(false);
                setEditing(null);
                setMsg(editing ? 'Dirección actualizada' : 'Dirección añadida');
                setTimeout(() => setMsg(''), 3000);
                load();
              }}
              onCancel={() => { setShowForm(false); setEditing(null); }}
            />
          </div>
        )}

        {loading ? (
          <div className="p-8 text-center text-stone-400">Cargando direcciones...</div>
        ) : addresses.length === 0 ? (
          <div className="bg-white border border-stone-200 rounded-xl p-8 text-center">
            <p className="text-3xl mb-2">📍</p>
            <p className="text-sm text-stone-500">No tienes direcciones guardadas</p>
          </div>
        ) : (
          <div className="space-y-3">
            {addresses.map((addr) => (
              <div
                key={addr.id}
                className={`bg-white border rounded-xl p-4 ${addr.isDefault ? 'border-[#2D6A4F] ring-1 ring-[#2D6A4F]/20' : 'border-stone-200'}`}
              >
                <div className="flex items-start justify-between">
                  <div>
                    {addr.label && (
                      <span className="inline-flex px-2 py-0.5 bg-stone-100 text-stone-600 text-xs font-medium rounded-full mb-1">
                        {addr.label}
                      </span>
                    )}
                    {addr.isDefault && (
                      <span className="inline-flex px-2 py-0.5 bg-[#2D6A4F]/10 text-[#2D6A4F] text-xs font-medium rounded-full mb-1 ml-1">
                        Predeterminada
                      </span>
                    )}
                    <p className="text-sm font-medium text-stone-900">{addr.recipientName}</p>
                    <p className="text-sm text-stone-600">{addr.street}</p>
                    <p className="text-sm text-stone-600">
                      {addr.postalCode} {addr.city}, {addr.country}
                    </p>
                  </div>
                  <div className="flex gap-2">
                    <button
                      onClick={() => { setEditing(addr); setShowForm(false); }}
                      className="text-xs text-[#2D6A4F] hover:underline"
                    >
                      Editar
                    </button>
                    <button
                      onClick={() => handleDelete(addr.id)}
                      className="text-xs text-red-500 hover:underline"
                    >
                      Eliminar
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}
