import { useState, useEffect } from 'react';
import { AdminService } from '../services/api';
import { UserPlus, Trash2, Edit3, Save, Key } from 'lucide-react';
import Modal from '../components/Modal';

interface AdminUser {
  id: number;
  username: string;
  nome?: string;
  email?: string;
  telefone?: string;
}

export default function AdminUsersPage() {
  const [admins, setAdmins] = useState<AdminUser[]>([]);
  const [loading, setLoading] = useState(true);

  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [editingAdmin, setEditingAdmin] = useState<AdminUser | null>(null);

  const [createForm, setCreateForm] = useState({ username: '', password: '', passwordConfirm: '' });
  const [editForm, setEditForm] = useState({ username: '', nome: '', email: '', telefone: '', password: '', passwordConfirm: '' });
  const [saving, setSaving] = useState(false);
  const [createError, setCreateError] = useState('');
  const [editError, setEditError] = useState('');

  const fetchAdmins = async () => {
    setLoading(true);
    try {
      const data = await AdminService.list();
      setAdmins(data);
    } catch {
      // interceptor handles 401
    } finally {
      setLoading(false);
    }
  };

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

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setCreateError('');
    if (createForm.password !== createForm.passwordConfirm) {
      setCreateError('As senhas não coincidem');
      return;
    }
    if (createForm.password.length < 4) {
      setCreateError('Senha deve ter no mínimo 4 caracteres');
      return;
    }
    setSaving(true);
    try {
      await AdminService.create({ username: createForm.username, password: createForm.password });
      setIsCreateOpen(false);
      setCreateForm({ username: '', password: '', passwordConfirm: '' });
      fetchAdmins();
    } catch (err: any) {
      setCreateError(err.response?.data?.error || 'Erro ao criar administrador');
    } finally {
      setSaving(false);
    }
  };

  const handleOpenEdit = (admin: AdminUser) => {
    setEditingAdmin(admin);
    setEditForm({ username: admin.username, nome: admin.nome || '', email: admin.email || '', telefone: admin.telefone || '', password: '', passwordConfirm: '' });
    setEditError('');
    setIsEditOpen(true);
  };

  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    setEditError('');
    if (editForm.password && editForm.password !== editForm.passwordConfirm) {
      setEditError('As senhas não coincidem');
      return;
    }
    if (editForm.password && editForm.password.length < 4) {
      setEditError('Senha deve ter no mínimo 4 caracteres');
      return;
    }
    if (!editingAdmin) return;
    setSaving(true);
    try {
      const body: any = { username: editForm.username, nome: editForm.nome, email: editForm.email, telefone: editForm.telefone };
      if (editForm.password) body.password = editForm.password;
      await AdminService.update(editingAdmin.id, body);
      setIsEditOpen(false);
      fetchAdmins();
    } catch (err: any) {
      setEditError(err.response?.data?.error || 'Erro ao atualizar');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (admin: AdminUser) => {
    if (!confirm(`Remover o administrador "${admin.username}"?`)) return;
    try {
      await AdminService.delete(admin.id);
      fetchAdmins();
    } catch (err: any) {
      alert(err.response?.data?.error || 'Erro ao remover');
    }
  };

  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">Administradores</h2>
          <p className="text-slate-400 mt-1 font-medium">Usuários com acesso ao painel administrativo.</p>
        </div>
        <button
          onClick={() => { setCreateError(''); setCreateForm({ username: '', password: '', passwordConfirm: '' }); setIsCreateOpen(true); }}
          className="flex items-center gap-2 px-6 py-3 bg-cyan-500 hover:bg-cyan-400 text-slate-950 font-black rounded-2xl transition-all shadow-lg shadow-cyan-500/20 uppercase italic text-xs active:scale-95"
        >
          <UserPlus size={18} />
          Novo Admin
        </button>
      </header>

      <div className="bg-slate-900/40 backdrop-blur-md border border-slate-800 rounded-[2.5rem] overflow-hidden">
        <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">Administrador</th>
                <th className="px-8 py-5">Contato</th>
                <th className="px-8 py-5">Status</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].map(i => (
                  <tr key={i} className="animate-pulse">
                    <td colSpan={4} className="px-8 py-8 bg-slate-800/5" />
                  </tr>
                ))
              ) : admins.length === 0 ? (
                <tr>
                  <td colSpan={4} className="px-8 py-20 text-center text-slate-500 font-medium italic">
                    Nenhum administrador encontrado.
                  </td>
                </tr>
              ) : admins.map(admin => (
                <tr key={admin.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-cyan-500/20 to-blue-600/20 border border-cyan-500/20 flex items-center justify-center text-cyan-400 font-black text-lg group-hover:scale-110 transition-transform">
                        {(admin.nome || admin.username).charAt(0).toUpperCase()}
                      </div>
                      <div>
                        <div className="text-white font-black text-sm uppercase tracking-tight">{admin.nome || admin.username}</div>
                        <div className="text-slate-500 text-[11px] font-bold">@{admin.username}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-8 py-6">
                    <div className="space-y-1">
                      <div className="text-xs text-slate-300 font-bold">{admin.email || '—'}</div>
                      <div className="text-xs text-slate-500 font-medium">{admin.telefone || '—'}</div>
                    </div>
                  </td>
                  <td className="px-8 py-6">
                    <span className="px-3 py-1 rounded-lg text-[10px] font-black uppercase tracking-widest bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                      Ativo
                    </span>
                  </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(admin)}
                        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(admin)}
                        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>

      {/* CREATE MODAL */}
      <Modal isOpen={isCreateOpen} onClose={() => setIsCreateOpen(false)} title="Novo Administrador">
        <form onSubmit={handleCreate} className="space-y-5">
          <div>
            <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Usuário *</label>
            <input
              required minLength={3}
              type="text"
              value={createForm.username}
              onChange={e => setCreateForm({ ...createForm, username: e.target.value })}
              placeholder="Ex: joao123"
              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">Senha *</label>
            <input
              required minLength={4}
              type="password"
              value={createForm.password}
              onChange={e => setCreateForm({ ...createForm, password: e.target.value })}
              placeholder="Mínimo 4 caracteres"
              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">Confirmar Senha *</label>
            <input
              required
              type="password"
              value={createForm.passwordConfirm}
              onChange={e => setCreateForm({ ...createForm, passwordConfirm: e.target.value })}
              placeholder="Repita a senha"
              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>
          {createError && (
            <p className="text-rose-400 text-sm font-medium">{createError}</p>
          )}
          <button
            type="submit"
            disabled={saving}
            className="w-full bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 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 mt-4"
          >
            <Save size={20} />
            {saving ? 'Criando...' : 'Criar Administrador'}
          </button>
        </form>
      </Modal>

      {/* EDIT MODAL */}
      <Modal isOpen={isEditOpen} onClose={() => setIsEditOpen(false)} title="Editar Administrador">
        <form onSubmit={handleEdit} className="space-y-5">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Usuário *</label>
              <input
                required
                type="text"
                value={editForm.username}
                onChange={e => setEditForm({ ...editForm, username: 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">Nome</label>
              <input
                type="text"
                value={editForm.nome}
                onChange={e => setEditForm({ ...editForm, 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>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">E-mail</label>
              <input
                type="email"
                value={editForm.email}
                onChange={e => setEditForm({ ...editForm, 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">Telefone</label>
              <input
                type="text"
                value={editForm.telefone}
                onChange={e => setEditForm({ ...editForm, 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 className="border-t border-slate-800 pt-5">
            <p className="text-[10px] font-black uppercase tracking-widest text-slate-500 mb-4 flex items-center gap-2">
              <Key size={12} /> Alterar Senha (opcional)
            </p>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">Nova Senha</label>
                <input
                  type="password"
                  value={editForm.password}
                  onChange={e => setEditForm({ ...editForm, password: e.target.value })}
                  placeholder="Deixe vazio para manter"
                  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">Confirmar</label>
                <input
                  type="password"
                  value={editForm.passwordConfirm}
                  onChange={e => setEditForm({ ...editForm, passwordConfirm: e.target.value })}
                  placeholder="Repita a nova senha"
                  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>
          {editError && (
            <p className="text-rose-400 text-sm font-medium">{editError}</p>
          )}
          <button
            type="submit"
            disabled={saving}
            className="w-full bg-cyan-500 hover:bg-cyan-400 disabled:opacity-50 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 mt-2"
          >
            <Save size={20} />
            {saving ? 'Salvando...' : 'Salvar Alterações'}
          </button>
        </form>
      </Modal>
    </div>
  );
}
