import { useState } from 'react';
import { LayoutDashboard, LogIn, AlertCircle, Users, Shield } from 'lucide-react';

interface LoginPageProps {
  onLogin: (type: 'admin' | 'team', accountData?: any) => void;
}

export default function LoginPage({ onLogin }: LoginPageProps) {
  const [credential, setCredential] = useState('');   // email ou username
  const [password, setPassword]     = useState('');
  const [loading, setLoading]       = useState(false);
  const [error, setError]           = useState('');

  // Detecta automaticamente: contém @ = funcionário, senão = admin
  const isEmail = credential.includes('@');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      if (isEmail) {
        // ── Login de funcionário (accounts) ──────────────────────────────
        const res = await fetch('/api/team/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({ email: credential, password }),
        });
        const data = await res.json();
        if (res.ok) {
          onLogin('team', data.account);
        } else {
          setError(data.error || 'Credenciais inválidas');
        }
      } else {
        // ── Login de admin (admins) ───────────────────────────────────────
        const res = await fetch('/admin/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          credentials: 'include',
          body: JSON.stringify({ username: credential, password }),
        });
        const data = await res.json();
        if (data.success) {
          onLogin('admin');
        } else {
          setError(data.error || 'Credenciais inválidas');
        }
      }
    } catch {
      setError('Erro de conexão com o servidor');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-black flex items-center justify-center p-4 relative">
      <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-cyan-500/5 rounded-full blur-3xl pointer-events-none" />

      <div className="relative w-full max-w-md animate-in fade-in slide-in-from-bottom-4 duration-500">
        <div className="bg-slate-900/80 backdrop-blur-xl border border-slate-800 rounded-[2rem] p-10 shadow-2xl">

          {/* Logo */}
          <div className="flex flex-col items-center mb-10">
            <div className="w-16 h-16 bg-gradient-to-br from-cyan-400 to-blue-600 rounded-2xl flex items-center justify-center shadow-lg shadow-cyan-500/20 mb-4">
              <LayoutDashboard className="text-white" size={32} />
            </div>
            <h1 className="text-2xl font-black text-white tracking-tighter">ALEMÃO</h1>
            <p className="text-[11px] text-cyan-500 font-black uppercase tracking-widest mt-1">Admin Cloud v2</p>
          </div>

          {/* indicador de tipo de login */}
          {credential && (
            <div className={`flex items-center justify-center gap-1.5 text-[11px] font-medium mb-4 px-3 py-1.5 rounded-full border w-fit mx-auto transition-all
              ${isEmail
                ? 'text-purple-400 border-purple-500/30 bg-purple-500/10'
                : 'text-cyan-400 border-cyan-500/30 bg-cyan-500/10'}`}>
              {isEmail
                ? <><Users size={11} /> Acesso de funcionário</>
                : <><Shield size={11} /> Acesso administrativo</>}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">
                {isEmail ? 'E-mail' : 'Usuário ou e-mail'}
              </label>
              <input
                required
                type="text"
                value={credential}
                onChange={e => setCredential(e.target.value)}
                placeholder="admin ou seu@email.com"
                autoComplete="username"
                className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white placeholder:text-slate-600 focus:ring-1 ring-cyan-500 outline-none transition-all"
              />
              <p className="text-[10px] text-slate-600 mt-1 pl-1">
                Admin: use seu nome de usuário &nbsp;·&nbsp; Funcionário: use seu e-mail
              </p>
            </div>

            <div>
              <label className="block text-[10px] font-black uppercase tracking-widest text-slate-500 mb-2">
                Senha
              </label>
              <input
                required
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="••••••••"
                autoComplete="current-password"
                className="w-full bg-slate-800/50 border border-slate-700 rounded-xl px-4 py-3 text-white placeholder:text-slate-600 focus:ring-1 ring-cyan-500 outline-none transition-all"
              />
            </div>

            {error && (
              <div className="flex items-center gap-2 p-4 bg-rose-500/10 border border-rose-500/20 rounded-xl text-rose-400 text-sm font-medium animate-in fade-in slide-in-from-top-2">
                <AlertCircle size={16} className="shrink-0" />
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              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 tracking-widest text-xs mt-2 active:scale-95"
            >
              <LogIn size={18} />
              {loading ? 'Entrando...' : 'Entrar'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
