import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { Lock, Mail, Flame, ArrowLeft, Eye, EyeOff, Loader2 } from 'lucide-react'
import api from '../services/api'

interface DemoUser {
  email: string;
  role: string;
  color: string;
}

const demoUsers: DemoUser[] = [
  { email: 'admin@hefesto.com', role: 'Admin', color: '#E65100' },
  { email: 'joao.santos@hefesto.com', role: 'Gestor', color: '#1A237E' },
  { email: 'ana.oliveira@hefesto.com', role: 'Financeiro', color: '#2E7D32' },
  { email: 'maria.silva@hefesto.com', role: 'Solicitante', color: '#7B1FA2' },
]

export default function Login() {
  const [email, setEmail] = useState('')
  const [senha, setSenha] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const navigate = useNavigate()

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError('')
    
    try {
      const { data } = await api.post('/auth/login', { email, senha })
      localStorage.setItem('token', data.access_token)
      localStorage.setItem('user', JSON.stringify(data.user))
      navigate('/app')
    } catch (err: any) {
      setError(err.response?.data?.message || 'Credenciais inválidas. Verifique e tente novamente.')
    } finally {
      setLoading(false)
    }
  }

  const fillDemoUser = (userEmail: string) => {
    setEmail(userEmail)
    setSenha('123456')
    setError('')
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-white flex items-center justify-center p-4 relative overflow-hidden">
      {/* Background decorations */}
      <div className="absolute top-0 right-0 w-[500px] h-[500px] bg-gradient-to-br from-primary/10 to-accent/5 rounded-full blur-3xl -translate-y-1/2 translate-x-1/3 pointer-events-none"></div>
      <div className="absolute bottom-0 left-0 w-[400px] h-[400px] bg-gradient-to-tr from-secondary/10 to-secondary/5 rounded-full blur-3xl translate-y-1/2 -translate-x-1/3 pointer-events-none"></div>
      
      <div className="w-full max-w-md relative animate-fade-in">
        {/* Back to home */}
        <Link 
          to="/" 
          className="inline-flex items-center gap-2 text-gray hover:text-primary transition-colors mb-8 group"
        >
          <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
          Voltar ao início
        </Link>

        {/* Logo and header */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-20 h-20 rounded-2xl bg-gradient-to-br from-primary to-accent mb-6 shadow-xl shadow-primary/30 animate-pulse-glow">
            <Flame className="w-10 h-10 text-white" />
          </div>
          <h1 className="text-3xl font-bold text-text mb-2">Nexus Facilities</h1>
          <p className="text-gray">Gestão de Facilities</p>
        </div>

        {/* Login card */}
        <div className="bg-white rounded-2xl p-8 shadow-xl border border-gray-100">
          <h2 className="text-xl font-semibold text-text mb-6 text-center">Acesse sua conta</h2>

          {error && (
            <div className="bg-red-50 border border-red-200 text-red-600 px-4 py-3 rounded-xl mb-6 text-sm flex items-start gap-3">
              <div className="w-5 h-5 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0 mt-0.5">
                <span className="text-red-500 text-xs font-bold">!</span>
              </div>
              {error}
            </div>
          )}

          <form onSubmit={handleLogin} className="space-y-5">
            <div>
              <label className="block text-sm font-medium text-text mb-2">E-mail</label>
              <div className="relative">
                <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-light" />
                <input 
                  type="email" 
                  value={email} 
                  onChange={e => setEmail(e.target.value)}
                  className="input-field pl-12"
                  placeholder="seu@email.com"
                  required
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-text mb-2">Senha</label>
              <div className="relative">
                <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-light" />
                <input 
                  type={showPassword ? 'text' : 'password'} 
                  value={senha} 
                  onChange={e => setSenha(e.target.value)}
                  className="input-field pl-12 pr-12"
                  placeholder="••••••"
                  required
                />
                <button 
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-light hover:text-primary transition-colors"
                >
                  {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              </div>
            </div>

            <button 
              type="submit" 
              disabled={loading || !email || !senha}
              className="w-full btn-primary py-4 text-lg flex items-center justify-center gap-2"
            >
              {loading ? (
                <Loader2 className="w-6 h-6 animate-spin" />
              ) : (
                'Entrar'
              )}
            </button>
          </form>

          {/* Demo users */}
          <div className="mt-8 pt-6 border-t border-gray-100">
            <p className="text-xs text-gray-light text-center mb-4">
              Usuários para demonstração — senha:{' '}
              <span className="text-primary font-semibold">123456</span>
            </p>
            <div className="grid grid-cols-2 gap-3">
              {demoUsers.map((user) => (
                <button
                  key={user.email}
                  type="button"
                  onClick={() => fillDemoUser(user.email)}
                  className={`text-left px-3 py-2.5 rounded-xl bg-card hover:bg-gray-100 transition-all border-2 ${
                    email === user.email ? 'border-primary' : 'border-transparent'
                  }`}
                >
                  <p className="text-xs text-text truncate font-medium">{user.email}</p>
                  <p className="text-[10px] font-semibold mt-0.5" style={{ color: user.color }}>
                    {user.role}
                  </p>
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Footer */}
        <p className="text-center text-gray-light text-sm mt-8">
          © 2026 Nexus Facilities. Todos os direitos reservados.
        </p>
      </div>
    </div>
  )
}
