import { useState, useEffect, useMemo } from 'react';
import { UserService } from '../services/api';
import { Users as UsersIconLucide, Search, Download, Trash2, Edit3, Save, Globe, Shield } from 'lucide-react';
import Modal from '../components/Modal';

export default function UsersPage() {
  const [users, setUsers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  
  // Modal State
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);
  const [formData, setFormData] = useState({
    nome: '',
    email: '',
    cpf: '',
    telefone: '',
    source: ''
  });

  const fetchUsers = async () => {
    setLoading(true);
    const data = await UserService.list();
    setUsers(data);
    setLoading(false);
  };

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

  // Filtered Users for Search
  const filteredUsers = useMemo(() => {
    return users.filter(user => 
      user.nome?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.cpf?.includes(searchTerm) ||
      user.telefone?.includes(searchTerm) ||
      user.email?.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [users, searchTerm]);

  const handleExportCSV = () => {
    const headers = ['ID', 'Nome', 'Email', 'CPF', 'Telefone', 'IP', 'Fonte', 'Data Cadastro'];
    const rows = filteredUsers.map(user => [
      user.id,
      user.nome,
      user.email || '',
      user.cpf || '',
      user.telefone || '',
      user.ip || '',
      user.source || '',
      new Date(user.timestamp || user.created_at).toLocaleString('pt-BR')
    ]);

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `leads_alemao_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
  };

  const handleOpenEdit = (user: any) => {
    setEditingUser(user);
    setFormData({
      nome: user.nome,
      email: user.email || '',
      cpf: user.cpf || '',
      telefone: user.telefone || '',
      source: user.source || 'hotspot'
    });
    setIsModalOpen(true);
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await UserService.update(editingUser.id, formData);
      setIsModalOpen(false);
      fetchUsers();
    } catch (err) {
      alert('Erro ao atualizar usuário');
    }
  };

  const handleDelete = async (id: number) => {
    if (confirm('Tem certeza que deseja remover este cliente da base?')) {
      try {
        await UserService.delete(id);
        fetchUsers();
      } catch (err) {
        alert('Erro ao excluir');
      }
    }
  };

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
      <header className="flex justify-between items-end">
        <div>
            <h2 className="text-3xl font-black text-white tracking-tighter uppercase italic">Clientes WiFi & Web</h2>
            <p className="text-slate-400 mt-1 font-medium">Gestão de leads captados pelo ecossistema.</p>
        </div>
        <button 
            onClick={handleExportCSV}
            className="flex items-center gap-2 px-6 py-3 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-2xl border border-slate-700 transition-all font-bold uppercase italic text-[10px] tracking-widest active:scale-95"
        >
            <Download size={18} />
            Exportar Leads (CSV)
        </button>
      </header>

      <div className="bg-slate-900/40 backdrop-blur-md border border-slate-800 rounded-[2.5rem] overflow-hidden">
        <div className="p-8 border-b border-slate-800 flex items-center gap-6">
            <div className="flex-1 relative group">
                <Search size={20} className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-500 group-focus-within:text-cyan-400 transition-colors" />
                <input 
                    type="text" 
                    value={searchTerm}
                    onChange={e => setSearchTerm(e.target.value)}
                    placeholder="Filtrar por nome, telefone, CPF ou e-mail..."
                    className="w-full bg-slate-800/50 border border-slate-700 rounded-2xl pl-14 pr-6 py-4 text-sm text-white placeholder:text-slate-600 focus:ring-1 ring-cyan-500 outline-none transition-all"
                />
            </div>
            <div className="hidden lg:flex items-center gap-4 px-6 py-3 bg-slate-800/20 border border-slate-800 rounded-2xl">
                <div className="flex flex-col">
                    <span className="text-[10px] text-slate-500 font-black uppercase tracking-widest">Total na Base</span>
                    <span className="text-white font-black tabular-nums">{users.length}</span>
                </div>
            </div>
        </div>
        
        <div className="overflow-x-auto">
            <table className="w-full text-left">
                <thead>
                    <tr className="bg-slate-800/30 text-slate-500 text-[10px] uppercase tracking-widest font-black">
                        <th className="px-8 py-5">Perfil do Cliente</th>
                        <th className="px-8 py-5">Identificação</th>
                        <th className="px-8 py-5">Origem / IP</th>
                        <th className="px-8 py-5 text-right">Ações</th>
                    </tr>
                </thead>
                <tbody className="divide-y divide-slate-800/50">
                    {loading ? (
                        [1,2,3,4,5].map(i => (
                            <tr key={i} className="animate-pulse">
                                <td colSpan={4} className="px-8 py-8 bg-slate-800/5" />
                            </tr>
                        ))
                    ) : filteredUsers.length === 0 ? (
                        <tr>
                            <td colSpan={4} className="px-8 py-20 text-center text-slate-500 font-medium italic">
                                Nenhum cliente encontrado para sua busca.
                            </td>
                        </tr>
                    ) : filteredUsers.map(user => (
                        <tr key={user.id} className="hover:bg-cyan-500/[0.02] transition-colors group">
                            <td className="px-8 py-6">
                                <div className="flex items-center gap-4">
                                    <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-slate-700 to-slate-800 flex items-center justify-center text-slate-500 border border-white/5 relative group-hover:scale-110 transition-transform">
                                        <UsersIconLucide size={24} />
                                        {user.source === 'hotspot' && (
                                            <div className="absolute -top-1 -right-1 w-4 h-4 bg-cyan-500 rounded-full border-2 border-slate-900 flex items-center justify-center">
                                                <Globe size={8} className="text-white" />
                                            </div>
                                        )}
                                    </div>
                                    <div>
                                        <div className="text-white font-black text-sm uppercase tracking-tight">{user.nome}</div>
                                        <div className="text-slate-500 text-[11px] font-bold">{user.email || 'SEM E-MAIL'}</div>
                                    </div>
                                </div>
                            </td>
                            <td className="px-8 py-6">
                                <div className="space-y-1">
                                    <div className="text-xs text-slate-300 font-bold flex items-center gap-2">
                                        <Shield size={12} className="text-slate-600" />
                                        {user.cpf || 'CPF NÃO INFO'}
                                    </div>
                                    <div className="text-xs text-cyan-400 font-black tabular-nums">{user.telefone || 'SEM TELEFONE'}</div>
                                </div>
                            </td>
                            <td className="px-8 py-6">
                                <div className="space-y-1">
                                    <div className={`text-[10px] font-black uppercase tracking-widest ${
                                        user.source === 'web' ? 'text-purple-400' : 'text-cyan-500'
                                    }`}>
                                        {user.source || 'hotspot'}
                                    </div>
                                    <div className="text-[10px] text-slate-500 font-bold tabular-nums">IP: {user.ip || '---'}</div>
                                </div>
                            </td>
                            <td className="px-8 py-6 text-right">
                                <div className="flex justify-end gap-3 translate-x-4 opacity-0 group-hover:opacity-100 group-hover:translate-x-0 transition-all">
                                    <button 
                                        onClick={() => handleOpenEdit(user)}
                                        className="p-3 bg-slate-800 text-slate-400 hover:text-white hover:bg-slate-700 rounded-xl transition-all border border-slate-700"
                                    >
                                        <Edit3 size={16} />
                                    </button>
                                    <button 
                                        onClick={() => handleDelete(user.id)}
                                        className="p-3 bg-rose-500/10 text-rose-500 hover:bg-rose-500 hover:text-white rounded-xl transition-all border border-rose-500/10"
                                    >
                                        <Trash2 size={16} />
                                    </button>
                                </div>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
      </div>

      {/* EDIT MODAL */}
      <Modal 
        isOpen={isModalOpen} 
        onClose={() => setIsModalOpen(false)} 
        title="Editar Perfil do Cliente"
      >
        <form onSubmit={handleSave} className="space-y-6">
            <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Nome Completo</label>
                <input 
                    required
                    type="text" 
                    value={formData.nome}
                    onChange={e => setFormData({...formData, nome: e.target.value})}
                    className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-cyan-500 outline-none transition-all"
                />
            </div>
            <div className="grid grid-cols-2 gap-4">
                <div>
                    <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">CPF</label>
                    <input 
                        type="text" 
                        value={formData.cpf}
                        onChange={e => setFormData({...formData, cpf: e.target.value})}
                        className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-cyan-500 outline-none transition-all"
                    />
                </div>
                <div>
                    <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Telefone</label>
                    <input 
                        type="text" 
                        value={formData.telefone}
                        onChange={e => setFormData({...formData, telefone: e.target.value})}
                        className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-cyan-500 outline-none transition-all"
                    />
                </div>
            </div>
            <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">E-mail</label>
                <input 
                    type="email" 
                    value={formData.email}
                    onChange={e => setFormData({...formData, email: e.target.value})}
                    className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-cyan-500 outline-none transition-all"
                />
            </div>
            <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Origem do Cadastro</label>
                <select 
                    value={formData.source}
                    onChange={e => setFormData({...formData, source: e.target.value})}
                    className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white focus:ring-1 ring-cyan-500 outline-none transition-all appearance-none"
                >
                    <option className="bg-slate-900 text-white" value="hotspot">WiFi Hotspot (Loja)</option>
                    <option className="bg-slate-900 text-white" value="web">Web (Site)</option>
                    <option className="bg-slate-900 text-white" value="manual">Manual (Balcão)</option>
                </select>
            </div>

            <button 
                type="submit"
                className="w-full bg-cyan-500 hover:bg-cyan-400 text-slate-950 font-black py-4 rounded-2xl flex items-center justify-center gap-2 transition-all shadow-lg shadow-cyan-500/20 uppercase italic text-sm"
            >
                <Save size={20} />
                Salvar Alterações
            </button>
        </form>
      </Modal>
    </div>
  );
}
