import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Users, Award, Search, Download, Trash2, Home, TrendingUp, AlertTriangle } from 'lucide-react';

export default function AdminPage() {
  const [leads, setLeads] = useState([]);
  const [filteredLeads, setFilteredLeads] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [showClearModal, setShowClearModal] = useState(false);

  // Carrega os leads do localStorage
  useEffect(() => {
    const data = JSON.parse(localStorage.getItem('leads_db') || '[]');
    // Ordena por data decrescente (mais recentes primeiro)
    const sortedData = data.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    setLeads(sortedData);
    setFilteredLeads(sortedData);
  }, []);

  // Filtra os leads conforme o termo de busca
  useEffect(() => {
    const filtered = leads.filter(l => 
      (l.nome && l.nome.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (l.email && l.email.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (l.cursoNome && l.cursoNome.toLowerCase().includes(searchTerm.toLowerCase()))
    );
    setFilteredLeads(filtered);
  }, [searchTerm, leads]);

  // Cálculos de Estatísticas
  const totalLeads = leads.length;
  const averageScore = totalLeads > 0 
    ? Math.round(leads.reduce((acc, curr) => acc + (curr.pontuacao || 0), 0) / totalLeads) 
    : 0;
  const perfectScores = leads.filter(l => l.pontuacao === 100).length;

  // Exportar dados para CSV
  const handleExportCSV = () => {
    if (leads.length === 0) {
      alert("Nenhum dado para exportar!");
      return;
    }
    const headers = ['Data/Hora', 'Nome', 'WhatsApp', 'E-mail', 'Curso ID', 'Curso Nome', 'Pontuação'];
    const rows = leads.map(l => [
      l.timestamp ? new Date(l.timestamp).toLocaleString('pt-BR') : '',
      l.nome || '',
      l.whatsapp || '',
      l.email || '',
      l.curso || '',
      l.cursoNome || '',
      l.pontuacao || 0
    ]);
    
    let csvContent = '\uFEFF'; // Adiciona o BOM do UTF-8 para o Excel reconhecer acentos corretamente
    csvContent += headers.join(';') + '\r\n';
    
    rows.forEach(row => {
      const escapedRow = row.map(val => `"${String(val).replace(/"/g, '""')}"`);
      csvContent += escapedRow.join(';') + '\r\n';
    });
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `leads_copaceunsp_${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // Limpar banco de dados
  const handleClearDatabase = () => {
    localStorage.removeItem('leads_db');
    setLeads([]);
    setFilteredLeads([]);
    setShowClearModal(false);
  };

  return (
    <div className="admin-container animate-fade-in">
      {/* Cabeçalho */}
      <div className="admin-header">
        <div>
          <h1 className="text-3xl font-bold text-gradient">Painel de Controle</h1>
          <p className="text-muted text-sm mt-1">Consulte os participantes e exporte os dados salvos no stand.</p>
        </div>
        <div className="flex gap-2">
          <button onClick={handleExportCSV} className="btn-primary" style={{ padding: '0.75rem 1.5rem', fontSize: '0.95rem' }} disabled={leads.length === 0}>
            <Download size={18} /> Exportar CSV
          </button>
          <Link to="/" className="btn-secondary" style={{ padding: '0.75rem 1.5rem', fontSize: '0.95rem' }}>
            <Home size={18} /> Início
          </Link>
        </div>
      </div>

      {/* Grid de Estatísticas */}
      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-icon">
            <Users size={24} />
          </div>
          <div>
            <div className="stat-val">{totalLeads}</div>
            <div className="stat-label">Total de Participantes</div>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon" style={{ background: 'rgba(255, 215, 0, 0.15)', color: 'var(--secondary-color)' }}>
            <TrendingUp size={24} />
          </div>
          <div>
            <div className="stat-val">{averageScore} pts</div>
            <div className="stat-label">Pontuação Média</div>
          </div>
        </div>

        <div className="stat-card">
          <div className="stat-icon" style={{ background: 'rgba(255, 255, 255, 0.1)', color: '#fff' }}>
            <Award size={24} />
          </div>
          <div>
            <div className="stat-val">{perfectScores}</div>
            <div className="stat-label">Gabaritaram (100 pts)</div>
          </div>
        </div>
      </div>

      {/* Barra de Busca e Ações Rápidas */}
      <div className="glass-panel" style={{ padding: '1.5rem', borderRadius: '1.5rem', marginBottom: '1.5rem' }}>
        <div className="search-container">
          <div className="flex-col form-group admin-search-input" style={{ marginBottom: 0 }}>
            <label className="form-label flex items-center gap-2">
              <Search size={14} /> Buscar Participante
            </label>
            <input 
              type="text" 
              className="form-input" 
              placeholder="Digite o nome, e-mail ou curso para filtrar..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              style={{ padding: '0.85rem' }}
            />
          </div>
          <button 
            onClick={() => setShowClearModal(true)} 
            className="btn-danger" 
            style={{ padding: '0.85rem 1.5rem', marginTop: '1.4rem', height: '48px', fontSize: '0.95rem', width: 'auto' }}
            disabled={leads.length === 0}
          >
            <Trash2 size={18} /> Limpar Banco
          </button>
        </div>
      </div>

      {/* Tabela de Leads */}
      <div className="table-wrapper">
        {filteredLeads.length > 0 ? (
          <table className="admin-table">
            <thead>
              <tr>
                <th>Data/Hora</th>
                <th>Nome</th>
                <th>E-mail</th>
                <th>WhatsApp</th>
                <th>Curso Escolhido</th>
                <th style={{ textAlign: 'center' }}>Pontuação</th>
              </tr>
            </thead>
            <tbody>
              {filteredLeads.map((item, idx) => {
                let badgeClass = 'badge-low';
                if (item.pontuacao === 80) badgeClass = 'badge-medium';
                if (item.pontuacao === 100) badgeClass = 'badge-high';

                return (
                  <tr key={idx}>
                    <td style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>
                      {item.timestamp ? new Date(item.timestamp).toLocaleString('pt-BR') : 'Sem data'}
                    </td>
                    <td style={{ fontWeight: '600' }}>{item.nome}</td>
                    <td>{item.email}</td>
                    <td>{item.whatsapp}</td>
                    <td>
                      <span style={{ fontSize: '0.85rem', background: 'rgba(255,255,255,0.05)', padding: '0.25rem 0.5rem', borderRadius: '0.5rem', border: '1px solid rgba(255,255,255,0.05)' }}>
                        {item.cursoNome || 'Geral'}
                      </span>
                    </td>
                    <td style={{ textAlign: 'center' }}>
                      <span className={`badge ${badgeClass}`}>
                        {item.pontuacao || 0} / 100 pts
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        ) : (
          <div className="no-data">
            <Users size={40} className="mb-2 text-muted" style={{ opacity: 0.5, margin: '0 auto 10px' }} />
            <p>Nenhum participante encontrado no banco de dados.</p>
          </div>
        )}
      </div>

      {/* Modal de Confirmação para Limpeza do Banco */}
      {showClearModal && (
        <div className="modal-overlay">
          <div className="modal-content">
            <AlertTriangle size={48} className="mb-4" style={{ color: 'var(--accent-color)', margin: '0 auto 16px' }} />
            <h3 className="text-xl font-bold mb-2">Excluir Todos os Dados?</h3>
            <p className="text-muted text-sm mb-6">
              Atenção: esta ação apagará permanentemente todos os leads cadastrados no localStorage deste computador. Essa ação não pode ser desfeita.
            </p>
            <div className="flex gap-4">
              <button onClick={handleClearDatabase} className="btn-primary" style={{ background: 'var(--accent-color)', flex: 1 }}>
                Sim, Excluir
              </button>
              <button onClick={() => setShowClearModal(false)} className="btn-secondary" style={{ flex: 1, border: '1px solid var(--text-muted)', color: 'var(--text-main)', background: 'transparent' }}>
                Cancelar
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
