import React, { useEffect, useState } from 'react';
import { FileText, Calendar, Users, Shield, Activity, TrendingUp, Zap } from 'lucide-react';
import api from '../services/api';
import { useAuth } from '../contexts/AuthContext';
import HardradaLogo from '../components/HardradaLogo';

const ACTION_LABEL: Record<string, string> = {
  LOGIN_SUCCESS:    'Login realizado',
  LOGIN_FAILED:     'Tentativa de login falhou',
  FILE_UPLOAD:      'Arquivo enviado',
  FILE_DOWNLOAD:    'Arquivo baixado',
  FILE_DELETE:      'Arquivo removido',
  USER_CREATED:     'Usuário criado',
  USER_UPDATED:     'Usuário editado',
  USER_DEACTIVATED: 'Usuário desativado',
};

const ACTION_COLOR: Record<string, string> = {
  LOGIN_SUCCESS:    'text-green-400',
  LOGIN_FAILED:     'text-red-400',
  FILE_UPLOAD:      'text-blue-400',
  FILE_DOWNLOAD:    'text-purple-400',
  FILE_DELETE:      'text-red-400',
  USER_CREATED:     'text-brand-cyan',
  USER_UPDATED:     'text-yellow-400',
  USER_DEACTIVATED: 'text-orange-400',
};

export default function Dashboard() {
  const { user, isAdmin } = useAuth();
  const [stats, setStats]       = useState({ files: 0, events: 0, users: 0 });
  const [recent, setRecent]     = useState<any[]>([]);
  const [loading, setLoading]   = useState(true);

  useEffect(() => {
    const load = async () => {
      try {
        const [fRes, aRes] = await Promise.all([api.get('/files'), api.get('/agenda')]);
        const s = { files: fRes.data.length, events: aRes.data.length, users: 0 };

        if (isAdmin) {
          const [uRes, auRes] = await Promise.all([api.get('/users'), api.get('/audit?limit=8')]);
          s.users = uRes.data.filter((u: any) => u.active).length;
          setRecent(auRes.data);
        }
        setStats(s);
      } finally { setLoading(false); }
    };
    load();
  }, [isAdmin]);

  const cards = [
    { label: 'Arquivos',       value: stats.files,  icon: FileText, color: 'text-brand-cyan',  ring: 'border-brand-cyan/20',   bg: 'bg-brand-cyan/10'  },
    { label: 'Eventos',        value: stats.events, icon: Calendar, color: 'text-violet-400',  ring: 'border-violet-400/20',  bg: 'bg-violet-400/10' },
    ...(isAdmin ? [
      { label: 'Usuários Ativos', value: stats.users, icon: Users, color: 'text-emerald-400', ring: 'border-emerald-400/20', bg: 'bg-emerald-400/10' },
    ] : []),
  ];

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="w-8 h-8 border-2 border-brand-cyan border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-6xl">
      {/* Welcome banner */}
      <div className="relative overflow-hidden rounded-2xl border border-brand-cyan/20 bg-gradient-to-br from-brand-navy via-brand-navy-dark to-surface-card p-6">
        <div className="absolute right-4 top-4 opacity-10">
          <HardradaLogo size={100} />
        </div>
        <div className="relative">
          <div className="flex items-center gap-2 mb-2">
            <Zap size={16} className="text-brand-cyan" />
            <span className="text-brand-cyan text-xs font-semibold uppercase tracking-wider">Sistema Online</span>
          </div>
          <h2 className="text-white text-2xl font-bold">
            Bem-vindo, {user?.name?.split(' ')[0]}
          </h2>
          <p className="text-gray-400 text-sm mt-1">
            {user?.role === 'admin' ? 'Administrador do sistema' : `${user?.department} — Colaborador`}
          </p>
        </div>
      </div>

      {/* Stats */}
      <div className={`grid gap-4 ${isAdmin ? 'grid-cols-1 sm:grid-cols-3' : 'grid-cols-1 sm:grid-cols-2'}`}>
        {cards.map(({ label, value, icon: Icon, color, ring, bg }) => (
          <div key={label} className={`card border ${ring}`}>
            <div className={`w-10 h-10 ${bg} rounded-xl flex items-center justify-center mb-4`}>
              <Icon size={20} className={color} />
            </div>
            <p className="text-white text-3xl font-bold">{value}</p>
            <p className="text-gray-500 text-sm mt-1">{label}</p>
          </div>
        ))}
      </div>

      {/* Recent activity */}
      {isAdmin && recent.length > 0 && (
        <div className="card">
          <div className="flex items-center gap-2 mb-5">
            <Activity size={16} className="text-brand-cyan" />
            <h3 className="text-white font-semibold">Atividade Recente</h3>
          </div>
          <div className="space-y-1">
            {recent.map((log) => (
              <div key={log.id} className="flex items-center justify-between py-2.5 border-b border-surface-border/40 last:border-0">
                <div className="flex items-center gap-3">
                  <span className={`w-1.5 h-1.5 rounded-full bg-current ${ACTION_COLOR[log.action] ?? 'text-gray-600'}`} />
                  <div>
                    <p className={`text-sm font-medium ${ACTION_COLOR[log.action] ?? 'text-gray-400'}`}>
                      {ACTION_LABEL[log.action] ?? log.action}
                    </p>
                    <p className="text-gray-600 text-xs">{log.user_email}</p>
                  </div>
                </div>
                <p className="text-gray-700 text-xs flex-shrink-0 ml-4">
                  {new Date(log.created_at).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
                </p>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
