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

export default function TaxRatesPage() {
  const [rates, setRates] = useState<TaxRate[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<string | null>(null);
  const [editName, setEditName] = useState('');
  const [editRate, setEditRate] = useState('');
  const [editActive, setEditActive] = useState(true);
  const [saving, setSaving] = useState(false);
  const [toggling, setToggling] = useState<Record<string, boolean>>({});
  const [msg, setMsg] = useState('');

  const [tipoEditing, setTipoEditing] = useState<string | null>(null);
  const [savingTipo, setSavingTipo] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try { const d = await taxApi.list(); setRates(d.items ?? []); }
    catch { /* silent */ }
    finally { setLoading(false); }
  }, []);

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

  const startEdit = (r: TaxRate) => {
    setEditing(r.id); setEditName(r.name); setEditRate(String(r.ratePercent)); setEditActive(r.active);
  };

  const handleSave = async (id: string) => {
    setSaving(true);
    try {
      await taxApi.update(id, { name: editName, ratePercent: parseFloat(editRate), active: editActive });
      setEditing(null); setMsg('Tipo impositivo actualizado'); setTimeout(() => setMsg(''), 3000); load();
    } catch (er) { alert(er instanceof Error ? er.message : 'Error'); }
    finally { setSaving(false); }
  };

  const fmt = (r: TaxRate) => `${r.ratePercent}%`;

  const toggleActive = async (id: string, newActive: boolean) => {
    setToggling(prev => ({ ...prev, [id]: true }));
    try {
      await taxApi.update(id, { active: newActive });
      setRates(prev => prev.map(r => r.id === id ? { ...r, active: newActive } : r));
    } catch (er) {
      alert(er instanceof Error ? er.message : 'Error al cambiar estado');
    } finally {
      setToggling(prev => ({ ...prev, [id]: false }));
    }
  };

  const saveTipo = async (id: string, newTipo: 'general' | 'reduced' | 'super-reduced') => {
    setSavingTipo(id);
    try {
      await taxApi.update(id, { appliesTo: newTipo });
      setRates(prev => prev.map(r => r.id === id ? { ...r, appliesTo: newTipo } : r));
      setTipoEditing(null);
    } catch (er) {
      alert(er instanceof Error ? er.message : 'Error al cambiar tipo');
    } finally {
      setSavingTipo(null);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Tipos impositivos (IVA)</h1>
        <p className="text-sm text-gray-500 mt-0.5">Configura los tipos de IVA aplicables a los productos.</p>
      </div>

      {msg && <div className="bg-green-50 text-green-700 text-sm px-4 py-2.5 rounded-xl border border-green-200">{msg}</div>}

      <div className="bg-white rounded-2xl border border-gray-200 overflow-hidden">
        <div className="px-6 py-4 border-b bg-gray-50">
          <h2 className="text-base font-semibold text-gray-800">IVA en España (ES)</h2>
        </div>

        {loading ? (
          <div className="flex items-center justify-center py-16 text-gray-400 text-sm">Cargando...</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 tracking-wide">Nombre</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Tipo</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Tasa</th>
                <th className="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Estado</th>
                <th className="text-right px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Acciones</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {rates.map(r => (
                <tr key={r.id} className="hover:bg-gray-50 transition-colors">
                  {editing === r.id ? (
                    <>
                      <td className="px-4 py-3">
                        <input value={editName} onChange={e => setEditName(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" />
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-500">{r.appliesTo}</td>
                      <td className="px-4 py-3">
                        <input type="number" step="0.01" value={editRate} onChange={e => setEditRate(e.target.value)}
                          className="w-24 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(editActive)} onChange={e => setEditActive(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 justify-end">
                          <button disabled={saving} onClick={() => handleSave(r.id)}
                            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={() => setEditing(null)}
                            className="px-3 py-1.5 border border-gray-300 text-gray-600 text-xs rounded-lg hover:bg-gray-50">Cancelar</button>
                        </div>
                      </td>
                    </>
                  ) : (
                    <>
                      <td className="px-6 py-4 text-sm font-medium text-gray-900">{r.name}</td>
                      <td className="px-6 py-4 text-sm text-gray-500">
                        {tipoEditing === r.id ? (
                          <select
                            autoFocus
                            defaultValue={r.appliesTo}
                            disabled={savingTipo === r.id}
                            onBlur={(e) => {
                              const next = e.target.value as 'general' | 'reduced' | 'super-reduced';
                              if (next !== r.appliesTo) saveTipo(r.id, next);
                              else setTipoEditing(null);
                            }}
                            onChange={(e) => {
                              const next = e.target.value as 'general' | 'reduced' | 'super-reduced';
                              if (next !== r.appliesTo) saveTipo(r.id, next);
                            }}
                            className="px-2 py-1 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none disabled:opacity-50"
                          >
                            <option value="general">General</option>
                            <option value="reduced">Reducido</option>
                            <option value="super-reduced">Superreducido</option>
                          </select>
                        ) : (
                          <button
                            onClick={() => setTipoEditing(r.id)}
                            title="Clic para cambiar tipo"
                            className="capitalize text-gray-500 hover:text-[#2D6A4F] cursor-text"
                          >
                            {r.appliesTo}
                          </button>
                        )}
                      </td>
                      <td className="px-6 py-4 text-sm font-bold text-gray-800">{fmt(r)}</td>
                      <td className="px-6 py-4">
                        <button
                          onClick={() => toggleActive(r.id, !r.active)}
                          disabled={toggling[r.id] || saving}
                          title={r.active ? 'Desactivar' : 'Activar'}
                          className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-[#2D6A4F] focus:ring-offset-2 ${
                            r.active ? 'bg-green-500' : 'bg-gray-300'
                          }`}
                        >
                          {toggling[r.id] ? (
                            <span className="w-full text-center text-white text-xs animate-pulse">…</span>
                          ) : (
                            <span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
                              r.active ? 'translate-x-6' : 'translate-x-1'
                            }`} />
                          )}
                        </button>
                      </td>
                      <td className="px-6 py-4 text-right">
                        {editing === r.id ? (
                          <div className="flex gap-1 justify-end">
                            <button disabled={saving} onClick={() => handleSave(r.id)}
                              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={() => setEditing(null)}
                              className="px-3 py-1.5 border border-gray-300 text-gray-600 text-xs rounded-lg hover:bg-gray-50">Cancelar</button>
                          </div>
                        ) : (
                          <RowActions onEdit={() => startEdit(r)} editTitle="Editar tipo" />
                        )}
                      </td>
                    </>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <div className="bg-amber-50 rounded-xl border border-amber-200 px-5 py-4">
        <p className="text-sm text-amber-800">
          <strong>España:</strong> IVA General 21%, IVA Reducido 10%, IVA Superreducido 4%. Los tipos se aplican a los precios sin IVA (netos) del producto.
        </p>
      </div>
    </div>
  );
}
