'use client';
import { useState, useEffect, useCallback } from 'react';
import { shippingApi, type ShippingZone, type ShippingMethod } from '@/lib/api-client';
import { RowActions } from '@/components/ui/RowActions';

type Tab = 'zones' | 'methods';

// ── Zone helpers ──────────────────────────────────────────────────────────────────
function ZoneRow({ zone, onEdit, onDelete }: { zone: ShippingZone; onEdit: () => void; onDelete: () => void }) {
  return (
    <tr className="hover:bg-gray-50 transition-colors">
      <td className="px-6 py-4 text-sm font-medium text-gray-900">{zone.name}</td>
      <td className="px-6 py-4 text-sm text-gray-600">{zone.country}</td>
      <td className="px-6 py-4 text-sm text-gray-500">{zone.postalCodePrefix ?? <span className="italic">Todos</span>}</td>
      <td className="px-6 py-4">
        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${zone.active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
          {zone.active ? 'Activo' : 'Inactivo'}
        </span>
      </td>
      <td className="px-6 py-4 text-right">
        <RowActions onEdit={onEdit} onDelete={onDelete} />
      </td>
    </tr>
  );
}

function ZoneForm({ zone, onSave, onCancel }: { zone?: ShippingZone; onSave: () => void; onCancel: () => void }) {
  const [name, setName] = useState(zone?.name ?? '');
  const [country, setCountry] = useState(zone?.country ?? '');
  const [prefix, setPrefix] = useState(zone?.postalCodePrefix ?? '');
  const [active, setActive] = useState(zone?.active ?? true);
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');

  const handle = async (e: React.FormEvent) => {
    e.preventDefault(); setSaving(true); setErr('');
    try {
      if (zone) {
        await shippingApi.updateZone(zone.id, { name, country, postalCodePrefix: prefix || null, active });
      } else {
        await shippingApi.createZone({ name, country, postalCodePrefix: prefix || null, active });
      }
      onSave(); onCancel();
    } catch (er) { setErr(er instanceof Error ? er.message : 'Error'); } finally { setSaving(false); }
  };

  return (
    <tr className="bg-green-50/50 border-b border-green-100">
      <td className="px-4 py-3"><input value={name} onChange={e => setName(e.target.value)} required placeholder="Nombre zona"
        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" /></td>
      <td className="px-4 py-3"><input value={country} onChange={e => setCountry(e.target.value)} required placeholder="ES, FR..."
        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" /></td>
      <td className="px-4 py-3"><input value={prefix} onChange={e => setPrefix(e.target.value)} placeholder="Ej: 28"
        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" /></td>
      <td className="px-4 py-3">
        <select value={String(active)} onChange={e => setActive(e.target.value === 'true')}
          className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none">
          <option value="true">Activo</option><option value="false">Inactivo</option></select></td>
      <td className="px-4 py-3">
        <div className="flex gap-1">
          <button disabled={saving} onClick={handle}
            className="px-3 py-1.5 bg-[#2D6A4F] text-white text-xs font-medium rounded-lg hover:bg-[#1B4332] disabled:opacity-50">
            {saving ? '...' : 'Guardar'}
          </button>
          <button onClick={onCancel}
            className="px-3 py-1.5 border border-gray-300 text-gray-600 text-xs rounded-lg hover:bg-white">Cancelar</button>
        </div>
        {err && <p className="text-xs text-red-600 mt-1">{err}</p>}
      </td>
    </tr>
  );
}

// ── Method helpers ───────────────────────────────────────────────────────────────
function MethodRow({ method, onEdit, onDelete }: { method: ShippingMethod; onEdit: () => void; onDelete: () => void }) {
  const fmt = (cents: number) => `€${(cents / 100).toFixed(2)}`;
  return (
    <tr className="hover:bg-gray-50 transition-colors">
      <td className="px-6 py-4">
        <p className="text-sm font-medium text-gray-900">{method.name}</p>
        {method.description && (
          <p className="text-xs text-gray-500 mt-0.5 max-w-xs">{method.description}</p>
        )}
      </td>
      <td className="px-6 py-4 text-sm text-gray-600">{method.zoneName}</td>
      <td className="px-6 py-4 text-sm font-semibold text-gray-800">{fmt(method.baseCostCents)}</td>
      <td className="px-6 py-4 text-sm text-gray-500">{method.freeShippingThresholdCents ? `Gratis desde ${fmt(method.freeShippingThresholdCents)}` : '—'}</td>
      <td className="px-6 py-4 text-sm text-gray-500">
        {method.maxWeightKg !== null ? `Máx ${method.maxWeightKg} kg` : '—'}
        {method.freeShippingMaxWeightKg !== null && (
          <span className="block text-xs text-gray-400">gratis hasta {method.freeShippingMaxWeightKg} kg</span>
        )}
      </td>
      <td className="px-6 py-4">
        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${method.active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
          {method.active ? 'Activo' : 'Inactivo'}
        </span>
      </td>
      <td className="px-6 py-4 text-right">
        <RowActions onEdit={onEdit} onDelete={onDelete} />
      </td>
    </tr>
  );
}

function MethodForm({ zones, method, onSave, onCancel }: { zones: ShippingZone[]; method?: ShippingMethod; onSave: () => void; onCancel: () => void }) {
  const [name, setName] = useState(method?.name ?? '');
  const [zoneId, setZoneId] = useState(method?.zoneId ?? zones[0]?.id ?? '');
  const [cost, setCost] = useState(method ? String(method.baseCostCents / 100) : '');
  const [threshold, setThreshold] = useState(method?.freeShippingThresholdCents ? String(method.freeShippingThresholdCents / 100) : '');
  const [description, setDescription] = useState(method?.description ?? '');
  const [maxWeight, setMaxWeight] = useState(method?.maxWeightKg != null ? String(method.maxWeightKg) : '');
  const [freeMaxWeight, setFreeMaxWeight] = useState(
    method?.freeShippingMaxWeightKg != null ? String(method.freeShippingMaxWeightKg) : '',
  );
  const [active, setActive] = useState(method?.active ?? true);
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');

  const handle = async (e: React.FormEvent) => {
    e.preventDefault(); setSaving(true); setErr('');
    try {
      const baseCostCents = Math.round(parseFloat(cost) * 100);
      const freeThreshold = threshold ? Math.round(parseFloat(threshold) * 100) : null;
      const descriptionPayload = description.trim() || null;
      const maxWeightPayload = maxWeight.trim() ? parseFloat(maxWeight.replace(',', '.')) : null;
      const freeMaxWeightPayload = freeMaxWeight.trim() ? parseFloat(freeMaxWeight.replace(',', '.')) : null;
      if (method) {
        await shippingApi.updateMethod(method.id, {
          name,
          baseCostCents,
          freeShippingThresholdCents: freeThreshold,
          description: descriptionPayload,
          maxWeightKg: maxWeightPayload,
          freeShippingMaxWeightKg: freeMaxWeightPayload,
          active,
        });
      } else {
        await shippingApi.createMethod({
          zoneId,
          name,
          baseCostCents,
          freeShippingThresholdCents: freeThreshold,
          description: descriptionPayload,
          maxWeightKg: maxWeightPayload,
          freeShippingMaxWeightKg: freeMaxWeightPayload,
          active,
        });
      }
      onSave(); onCancel();
    } catch (er) { setErr(er instanceof Error ? er.message : 'Error'); } finally { setSaving(false); }
  };

  return (
    <tr className="bg-green-50/50 border-b border-green-100">
      <td className="px-4 py-3">
        <input value={name} onChange={e => setName(e.target.value)} required placeholder="Nombre método"
          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
        <input value={description} onChange={e => setDescription(e.target.value)} placeholder="Descripción para el checkout"
          className="w-full px-3 py-2 mt-1.5 border border-gray-300 rounded-lg text-xs focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
      </td>
      <td className="px-4 py-3">
        <select value={zoneId} onChange={e => setZoneId(e.target.value)}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none">
          {zones.map(z => <option key={z.id} value={z.id}>{z.name}</option>)}
        </select></td>
      <td className="px-4 py-3"><input type="number" step="0.01" value={cost} onChange={e => setCost(e.target.value)} required placeholder="0.00"
        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" /></td>
      <td className="px-4 py-3"><input type="number" step="0.01" value={threshold} onChange={e => setThreshold(e.target.value)} placeholder="Sin gratis"
        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" /></td>
      <td className="px-4 py-3">
        <input type="number" step="0.001" min="0" value={maxWeight} onChange={e => setMaxWeight(e.target.value)} placeholder="Sin límite"
          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-xs focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
        <input type="number" step="0.001" min="0" value={freeMaxWeight} onChange={e => setFreeMaxWeight(e.target.value)} placeholder="Gratis hasta kg"
          className="w-full px-3 py-2 mt-1.5 border border-gray-300 rounded-lg text-xs focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
      </td>
      <td className="px-4 py-3">
        <select value={String(active)} onChange={e => setActive(e.target.value === 'true')}
          className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none">
          <option value="true">Activo</option><option value="false">Inactivo</option></select></td>
      <td className="px-4 py-3">
        <div className="flex gap-1">
          <button disabled={saving} onClick={handle}
            className="px-3 py-1.5 bg-[#2D6A4F] text-white text-xs font-medium rounded-lg hover:bg-[#1B4332] disabled:opacity-50">
            {saving ? '...' : 'Guardar'}
          </button>
          <button onClick={onCancel}
            className="px-3 py-1.5 border border-gray-300 text-gray-600 text-xs rounded-lg hover:bg-white">Cancelar</button>
        </div>
        {err && <p className="text-xs text-red-600 mt-1">{err}</p>}
      </td>
    </tr>
  );
}

// ── Main page ─────────────────────────────────────────────────────────────────────
export default function ShippingPage() {
  const [tab, setTab] = useState<Tab>('zones');
  const [zones, setZones] = useState<ShippingZone[]>([]);
  const [methods, setMethods] = useState<ShippingMethod[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingZone, setEditingZone] = useState<ShippingZone | null>(null);
  const [editingMethod, setEditingMethod] = useState<ShippingMethod | null>(null);
  const [showZoneForm, setShowZoneForm] = useState(false);
  const [showMethodForm, setShowMethodForm] = useState(false);
  const [msg, setMsg] = useState('');

  const loadZones = useCallback(async () => {
    try { const d = await shippingApi.listZones(); setZones(d.items ?? []); }
    catch { /* silent */ }
  }, []);

  const loadMethods = useCallback(async () => {
    try { const d = await shippingApi.listMethods(); setMethods(d.items ?? []); }
    catch { /* silent */ }
  }, []);

  const load = useCallback(async () => {
    setLoading(true);
    await Promise.all([loadZones(), loadMethods()]);
    setLoading(false);
  }, [loadZones, loadMethods]);

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

  const handleDeleteZone = async (id: string) => {
    if (!confirm('¿Eliminar esta zona y todos sus métodos?')) return;
    try { await shippingApi.deleteZone(id); setMsg('Zona eliminada'); setTimeout(() => setMsg(''), 3000); loadZones(); }
    catch (er) { alert(er instanceof Error ? er.message : 'Error'); }
  };

  const handleDeleteMethod = async (id: string) => {
    if (!confirm('¿Eliminar este método de envío?')) return;
    try { await shippingApi.deleteMethod(id); setMsg('Método eliminado'); setTimeout(() => setMsg(''), 3000); loadMethods(); }
    catch (er) { alert(er instanceof Error ? er.message : 'Error'); }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Envíos</h1>
        {msg && <span className="text-sm text-green-600 bg-green-50 px-3 py-1 rounded-full">{msg}</span>}
      </div>

      {/* Tabs */}
      <div className="flex gap-1 border-b border-gray-200">
        {([['zones', 'Zonas de envío'], ['methods', 'Métodos de envío']] as [Tab, string][]).map(([t, label]) => (
          <button key={t} onClick={() => setTab(t)}
            className={`px-5 py-2.5 text-sm font-medium border-b-2 -mb-px transition-colors ${tab === t ? 'border-[#2D6A4F] text-[#2D6A4F]' : 'border-transparent text-gray-500 hover:text-gray-700'}`}>
            {label}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-16 text-gray-400 text-sm">Cargando...</div>
      ) : tab === 'zones' ? (
        <div className="bg-white rounded-2xl border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 border-b flex items-center justify-between">
            <h2 className="text-base font-semibold text-gray-800">Zonas ({zones.length})</h2>
            <button onClick={() => { setShowZoneForm(true); setEditingZone(null); }}
              className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] text-white text-sm font-semibold rounded-xl transition-colors">
              + Nueva zona
            </button>
          </div>
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Nombre</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">País</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">CP prefijo</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Estado</th>
                <th className="text-right px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Acciones</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {showZoneForm && !editingZone && (
                <ZoneForm onSave={loadZones} onCancel={() => setShowZoneForm(false)} />
              )}
              {editingZone && (
                <ZoneForm zone={editingZone} onSave={() => { setEditingZone(null); loadZones(); }} onCancel={() => setEditingZone(null)} />
              )}
              {zones.length === 0 && !showZoneForm ? (
                <tr><td colSpan={5} className="px-6 py-12 text-center text-gray-400 text-sm">Sin zonas de envío</td></tr>
              ) : zones.map(z => (
                <ZoneRow key={z.id} zone={z} onEdit={() => { setEditingZone(z); setShowZoneForm(false); }}
                  onDelete={() => handleDeleteZone(z.id)} />
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="bg-white rounded-2xl border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 border-b flex items-center justify-between">
            <h2 className="text-base font-semibold text-gray-800">Métodos ({methods.length})</h2>
            <button onClick={() => { setShowMethodForm(true); setEditingMethod(null); }}
              className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] text-white text-sm font-semibold rounded-xl transition-colors"
              disabled={zones.length === 0}>
              + Nuevo método
            </button>
          </div>
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Nombre</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Zona</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Coste</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Envío gratis</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Peso</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Estado</th>
                <th className="text-right px-6 py-3 text-xs font-semibold text-gray-500 uppercase">Acciones</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {showMethodForm && !editingMethod && (
                <MethodForm zones={zones} onSave={loadMethods} onCancel={() => setShowMethodForm(false)} />
              )}
              {editingMethod && (
                <MethodForm zones={zones} method={editingMethod} onSave={() => { setEditingMethod(null); loadMethods(); }} onCancel={() => setEditingMethod(null)} />
              )}
              {methods.length === 0 && !showMethodForm ? (
                <tr><td colSpan={7} className="px-6 py-12 text-center text-gray-400 text-sm">
                  {zones.length === 0 ? 'Crea primero una zona de envío' : 'Sin métodos de envío'}
                </td></tr>
              ) : methods.map(m => (
                <MethodRow key={m.id} method={m} onEdit={() => { setEditingMethod(m); setShowMethodForm(false); }}
                  onDelete={() => handleDeleteMethod(m.id)} />
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
