import React, { useState, useEffect } from 'react';
import Layout from '../components/Layout';
import { History, Siren, ShieldAlert, Bell, Clock } from 'lucide-react';
import { getHistorial } from '../lib/api';

export default function HistorialPage() {
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getHistorial(100).then(d => { setEvents(d); setLoading(false); }).catch(() => setLoading(false));
  }, []);

  const iconMap = { on: Siren, off: Siren, sos: ShieldAlert, test: Bell };

  return (
    <Layout>
      <div className="space-y-4">
        <h1 className="font-black text-2xl uppercase tracking-tight flex items-center gap-3">
          <History className="h-7 w-7 text-blue-500" /> Historial
        </h1>
        {loading ? (
          <div className="space-y-2">{[...Array(5)].map((_, i) => <div key={i} className="h-16 bg-zinc-200 dark:bg-zinc-800 rounded-xl animate-pulse" />)}</div>
        ) : events.length === 0 ? (
          <p className="text-center py-12 text-zinc-400">Sin eventos registrados</p>
        ) : (
          <div className="space-y-2">
            {events.map(ev => {
              const Icon = iconMap[ev.action] || Clock;
              const isOn = ev.action === 'on';
              const isSos = ev.action === 'sos';
              return (
                <div key={ev.id} className={`flex items-center gap-3 p-3 border rounded-xl ${isSos ? 'bg-red-50 border-red-200 dark:bg-red-950/20 dark:border-red-900' : ''}`}>
                  <div className={`p-2 rounded-full ${isSos ? 'bg-red-100 text-red-500' : isOn ? 'bg-emerald-100 text-emerald-600' : 'bg-zinc-100 text-zinc-500'}`}>
                    <Icon className="h-4 w-4" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="font-bold text-sm">{ev.dispositivo_nombre || ev.action.toUpperCase()}</span>
                      <span className={`text-xs font-black uppercase px-1.5 py-0.5 rounded ${isOn ? 'bg-red-100 text-red-600' : isSos ? 'bg-red-500 text-white' : ev.action === 'test' ? 'bg-blue-100 text-blue-600' : 'bg-zinc-200 text-zinc-600'}`}>
                        {ev.action}
                      </span>
                    </div>
                    <span className="text-xs text-zinc-400">{ev.usuario_nombre}</span>
                  </div>
                  <span className="text-xs text-zinc-400 shrink-0">
                    {ev.created_at && new Date(ev.created_at).toLocaleString('es-CL', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
                  </span>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </Layout>
  );
}
