import { useState, useEffect } from 'react';
import api from '../../services/api';
import { History, User as UserIcon, CheckCircle, XCircle, FileText, Clock } from 'lucide-react';

interface AuditLog {
  id: number;
  action: string;
  username: string;
  createdAt: string;
  details: string;
}

export default function AuditTimeline() {
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/reports/audit').then(res => {
      setLogs(res.data);
      setLoading(false);
    });
  }, []);

  const getIcon = (action: string) => {
    if (action === 'Aprobar') return <CheckCircle className="text-green-500" size={18} />;
    if (action === 'Rechazar') return <XCircle className="text-red-500" size={18} />;
    return <FileText className="text-blue-500" size={18} />;
  };

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div className="flex items-center gap-2">
        <History className="text-blue-600" />
        <h2 className="text-2xl font-bold text-gray-800">Auditoría de Actividad</h2>
      </div>

      <div className="bg-white rounded-xl border shadow-sm overflow-hidden">
        <div className="p-4 bg-gray-50 border-b font-bold text-gray-600 text-sm">
          Últimas acciones realizadas por el equipo
        </div>

        <div className="divide-y">
          {loading ? (
            <div className="p-10 text-center text-gray-400 italic">Cargando historial...</div>
          ) : logs.map(log => (
            <div key={log.id} className="p-4 hover:bg-gray-50 transition flex items-start gap-4">
              <div className="mt-1">{getIcon(log.action)}</div>
              <div className="flex-1">
                <div className="flex justify-between">
                  <span className="font-bold text-gray-800 flex items-center gap-1 italic">
                    <UserIcon size={14} className="text-gray-400" /> {log.username}
                  </span>
                  <span className="text-xs text-gray-400 flex items-center gap-1">
                    <Clock size={12} /> {new Date(log.createdAt).toLocaleString()}
                  </span>
                </div>
                <p className="text-sm text-gray-600 mt-1">{log.details}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}