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

interface Promo { code: string; type: string; value: number; startsAt: string; endsAt: string; active: boolean; usageLimit: number | null; usageCount: number; }

export default function PromotionsPage() {
  const [items, setItems] = useState<Promo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [msg, setMsg] = useState('');

  const [form, setForm] = useState({
    code: '', type: 'percent', value: '',
    startsAt: new Date().toISOString().split('T')[0],
    endsAt: new Date(Date.now() + 30 * 86400000).toISOString().split('T')[0],
    usageLimit: '',
  });

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const d = await promotionsApi.list() as { items: Promo[] };
      setItems(d.items ?? []);
    } catch (e) { setError(e instanceof Error ? e.message : 'Error'); }
    finally { setLoading(false); }
  }, []);

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

  const handleSave = async () => {
    setMsg('');
    try {
      await promotionsApi.create({
        code: form.code,
        type: form.type,
        value: parseInt(form.value, 10),
        startsAt: new Date(form.startsAt).toISOString(),
        endsAt: new Date(form.endsAt).toISOString(),
        usageLimit: form.usageLimit ? parseInt(form.usageLimit, 10) : null,
      });
      setMsg('Promoción creada');
      setShowForm(false);
      load();
    } catch (e) { setMsg(e instanceof Error ? e.message : 'Error'); }
  };

  const toggleActive = async (code: string, currentActive: boolean) => {
    try {
      await promotionsApi.update(code, { active: !currentActive });
      load();
    } catch (e) { alert(e instanceof Error ? e.message : 'Error'); }
  };

  const handleDelete = async (code: string) => {
    if (!confirm(`¿Eliminar "${code}"?`)) return;
    try { await promotionsApi.delete(code); load(); }
    catch (e) { alert(e instanceof Error ? e.message : 'Error'); }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Promociones</h1>
        <button onClick={() => setShowForm(true)} className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] text-white text-sm font-semibold rounded-xl">+ Nueva promoción</button>
      </div>

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

      {showForm && (
        <div className="bg-white border border-gray-200 rounded-xl p-6 space-y-4">
          <h2 className="font-semibold text-gray-900">Nueva promoción</h2>
          <div className="grid grid-cols-2 gap-4">
            {[['code','Código *','text'],['value','Valor *','number']].map(([k, label, t]) => (
              <div key={k}>
                <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
                <input type={t} value={(form as Record<string,string>)[k]} onChange={e => setForm({...form, [k]: e.target.value})} className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
              </div>
            ))}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Tipo</label>
              <select value={form.type} onChange={e => setForm({...form, type: e.target.value})} className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm bg-white focus:ring-2 focus:ring-[#2D6A4F] outline-none">
                <option value="percent">Porcentaje</option><option value="fixed_amount">Cantidad fija</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Límite de uso</label>
              <input type="number" value={form.usageLimit} onChange={e => setForm({...form, usageLimit: e.target.value})} placeholder="Sin límite" className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Fecha inicio</label>
              <input type="date" value={form.startsAt} onChange={e => setForm({...form, startsAt: e.target.value})} className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Fecha fin</label>
              <input type="date" value={form.endsAt} onChange={e => setForm({...form, endsAt: e.target.value})} className="w-full px-4 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none" />
            </div>
          </div>
          <div className="flex gap-3">
            <button onClick={handleSave} className="px-5 py-2.5 bg-[#2D6A4F] hover:bg-[#1B4332] text-white text-sm font-semibold rounded-xl">Crear</button>
            <button onClick={() => setShowForm(false)} className="px-5 py-2.5 border border-gray-300 text-gray-600 text-sm rounded-xl">Cancelar</button>
          </div>
        </div>
      )}

      <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
        {loading ? <div className="p-12 text-center text-gray-400">Cargando...</div> :
         error ? <div className="text-center text-red-600">{error}</div> :
         items.length === 0 ? <div className="p-12 text-center text-gray-400">No hay promociones</div> :
         <table className="w-full">
           <thead><tr className="bg-gray-50 border-b border-gray-200">
             {['Código','Tipo','Valor','Activa','Límite','Usos','Fin'].map(h => <th key={h} className="text-left text-xs font-semibold text-gray-500 uppercase tracking-wide px-4 py-3">{h}</th>)}
             <th className="px-4 py-3"></th>
           </tr></thead>
           <tbody className="divide-y divide-gray-50">
             {items.map(p => (
               <tr key={p.code} className="hover:bg-gray-50">
                 <td className="px-4 py-3.5 font-mono text-sm font-medium text-gray-900">{p.code}</td>
                 <td className="px-4 py-3.5 text-sm text-gray-600">{p.type === 'percent' ? '%' : 'Fijo'}</td>
                 <td className="px-4 py-3.5 text-sm font-medium text-gray-900">{p.type === 'percent' ? `${p.value / 100}%` : `€${(p.value / 100).toFixed(2)}`}</td>
                 <td className="px-4 py-3.5">
                   <button onClick={() => toggleActive(p.code, p.active)} className={`px-2 py-0.5 rounded-full text-xs font-medium ${p.active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>{p.active ? 'Sí' : 'No'}</button>
                 </td>
                 <td className="px-4 py-3.5 text-sm text-gray-500">{p.usageLimit ?? '∞'}</td>
                 <td className="px-4 py-3.5 text-sm text-gray-500">{p.usageCount}</td>
                 <td className="px-4 py-3.5 text-sm text-gray-500">{new Date(p.endsAt).toLocaleDateString('es-ES')}</td>
                 <td className="px-4 py-3.5"><RowActions onDelete={() => handleDelete(p.code)} /></td>
               </tr>
             ))}
           </tbody>
         </table>
        }
      </div>
    </div>
  );
}
