'use client'

import React, { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Lock, Mail, ArrowRight, ShieldAlert, Sparkles, User } from 'lucide-react'
import { useAuth } from '../context/AuthContext'
import { authApi } from '../services/chatApiService'
import { Input, Button } from '@/components/ui'

type Mode = 'login-user' | 'login-admin' | 'register'

export default function LoginPage() {
  const { login } = useAuth()
  const [mode, setMode] = useState<Mode>('login-user')
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  const isRegister = mode === 'register'
  const isAdmin = mode === 'login-admin'

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

    try {
      let res: any

      if (isRegister) {
        if (!name.trim()) { setError('Nome é obrigatório.'); setLoading(false); return }
        res = await authApi.register({ name: name.trim(), email, password })
      } else {
        res = await authApi.login({ email, password })
        // Admin check
        if (isAdmin && res.user?.role !== 'ADMIN') {
          setError('Acesso restrito a administradores.')
          setLoading(false)
          return
        }
      }

      if (res.accessToken) {
        login(
          res.accessToken,
          {
            id: res.user?.id ?? '',
            email: res.user?.email ?? email,
            name: res.user?.name ?? name,
            role: (res.user?.role ?? 'USER').toLowerCase() as 'user' | 'admin',
            daysRemaining: res.user?.daysRemaining,
          },
          res.refreshToken
        )
      } else {
        setError('Credenciais inválidas.')
      }
    } catch (err: any) {
      const msg = err.response?.data?.error ?? err.response?.data?.message ?? 'Erro ao conectar com o servidor.'
      setError(msg)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-surface flex relative overflow-hidden font-sans">
      {/* Ambient glow */}
      <div className="absolute top-[-20%] left-[-10%] w-[500px] h-[500px] rounded-full bg-brand-600/20 blur-[120px] pointer-events-none animate-float" />
      <div className="absolute bottom-[-20%] right-[-10%] w-[600px] h-[600px] rounded-full bg-blue-600/10 blur-[150px] pointer-events-none animate-float" style={{ animationDelay: '3s' }} />

      <div className="w-full max-w-7xl mx-auto p-6 relative z-10 grid lg:grid-cols-2 gap-12 items-center min-h-[calc(100vh-80px)]">

        {/* Left — Brand */}
        <div className="hidden lg:flex flex-col justify-center space-y-8 pr-12">
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.7 }}>
            <div className="flex items-center gap-3 mb-6">
              <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-brand-500 to-brand-700 flex items-center justify-center shadow-glow-brand">
                <Sparkles className="text-white w-6 h-6" />
              </div>
              <span className="text-3xl font-black text-white tracking-tight">
                new<span className="text-brand-400">whats</span>
              </span>
            </div>
            <h1 className="text-5xl font-black text-white leading-[1.1] tracking-tight">
              Atendimento<br />
              <span className="text-transparent bg-clip-text bg-gradient-to-r from-brand-400 to-blue-400">
                inteligente
              </span>
            </h1>
            <p className="mt-6 text-lg text-slate-400 leading-relaxed max-w-md">
              CRM omnichannel com IA, Temporal e WhatsApp multi-device. Escale seu atendimento sem perder o toque humano.
            </p>
          </motion.div>

          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.3 }}
            className="flex items-center gap-4 mt-8 pt-8 border-t border-white/5">
            <div className="flex -space-x-3">
              {[1, 2, 3, 4].map(i => (
                <div key={i} className="w-10 h-10 rounded-full border-2 border-surface bg-gradient-to-br from-brand-400 to-blue-500" />
              ))}
            </div>
            <div className="text-sm">
              <p className="text-white font-semibold">Plataforma White-Label</p>
              <p className="text-slate-500">Infraestrutura dedicada por tenant</p>
            </div>
          </motion.div>
        </div>

        {/* Right — Form */}
        <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} transition={{ duration: 0.5, delay: 0.2 }}
          className="w-full max-w-md mx-auto">
          <div className="glass-elevated rounded-3xl p-8 shadow-premium relative overflow-hidden shimmer-line">

            <div className="text-center mb-8">
              <h2 className="text-2xl font-bold text-white mb-2">
                {isRegister ? 'Criar conta' : 'Bem-vindo de volta'}
              </h2>
              <p className="text-slate-400 text-sm">
                {isRegister ? 'Comece seu trial gratuito de 14 dias' : 'Entre para gerenciar seu workspace'}
              </p>
            </div>

            {/* Mode tabs */}
            <div className="flex p-1 bg-white/5 rounded-xl mb-8 gap-1">
              {(['login-user', 'login-admin', 'register'] as Mode[]).map((m) => {
                const labels: Record<Mode, string> = { 'login-user': 'Entrar', 'login-admin': 'Admin', 'register': 'Registrar' }
                const activeClass: Record<Mode, string> = {
                  'login-user': 'bg-brand-500 text-white shadow-lg shadow-brand-500/20',
                  'login-admin': 'bg-slate-700 text-white shadow-lg shadow-slate-900/50',
                  'register': 'bg-emerald-600 text-white shadow-lg shadow-emerald-900/40',
                }
                return (
                  <button key={m} onClick={() => { setMode(m); setError(''); setSuccess('') }}
                    className={`flex-1 py-2.5 text-sm font-semibold rounded-lg transition-all duration-200 ${mode === m ? activeClass[m] : 'text-slate-400 hover:text-white'}`}>
                    {labels[m]}
                  </button>
                )
              })}
            </div>

            {/* Mensagens */}
            <AnimatePresence mode="wait">
              {error && (
                <motion.div key="err" initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} exit={{ opacity: 0, height: 0 }}
                  className="bg-red-500/10 border border-red-500/20 rounded-xl p-4 mb-6 flex items-start gap-3">
                  <ShieldAlert className="w-5 h-5 text-red-400 shrink-0 mt-0.5" />
                  <p className="text-sm text-red-200">{error}</p>
                </motion.div>
              )}
              {success && (
                <motion.div key="ok" initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} exit={{ opacity: 0, height: 0 }}
                  className="bg-emerald-500/10 border border-emerald-500/20 rounded-xl p-4 mb-6">
                  <p className="text-sm text-emerald-300">{success}</p>
                </motion.div>
              )}
            </AnimatePresence>

            <form onSubmit={handleSubmit} className="space-y-5">

              {/* Nome — só no register */}
              <AnimatePresence>
                {isRegister && (
                  <motion.div key="name-field" initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} exit={{ opacity: 0, height: 0 }}>
                    <Input
                      icon={<User className="w-5 h-5" />}
                      label="Nome completo"
                      type="text"
                      required
                      value={name}
                      onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value)}
                      placeholder="Seu nome"
                    />
                  </motion.div>
                )}
              </AnimatePresence>

              <Input
                icon={<Mail className="w-5 h-5" />}
                label="E-mail"
                type="email"
                required
                value={email}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
                placeholder="voce@empresa.com"
              />

              <div className="space-y-1.5">
                <div className="flex justify-between items-center ml-1">
                  <label className="text-xs font-semibold text-slate-400 uppercase tracking-wider">Senha</label>
                  {!isRegister && (
                    <button type="button" className="text-xs font-semibold text-brand-400 hover:text-brand-300 transition-colors">
                      Esqueceu?
                    </button>
                  )}
                </div>
                <div className="relative">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-500" />
                  <input
                    type="password"
                    autoComplete={isRegister ? 'new-password' : 'current-password'}
                    required
                    minLength={8}
                    value={password}
                    onChange={e => setPassword(e.target.value)}
                    className="w-full bg-black/30 border border-white/10 rounded-xl py-3 pl-12 pr-4 text-white placeholder:text-slate-600 focus:outline-none focus:ring-2 focus:ring-brand-500/40 focus:border-brand-500/50 transition-all"
                    placeholder="••••••••"
                  />
                </div>
                {isRegister && (
                  <p className="text-xs text-slate-500 ml-1">Mínimo 8 caracteres.</p>
                )}
              </div>

              <Button
                variant="premium"
                size="lg"
                loading={loading}
                type="submit"
                className="w-full mt-4"
                icon={!loading ? <ArrowRight className="w-4 h-4" /> : undefined}
              >
                {isRegister ? 'Criar conta grátis' : isAdmin ? 'Entrar como Admin' : 'Entrar'}
              </Button>
            </form>

            {mode === 'login-user' && (
              <p className="mt-8 text-center text-sm text-slate-400">
                Não tem conta?{' '}
                <button onClick={() => setMode('register')} className="font-semibold text-white hover:text-brand-400 transition-colors">
                  Comece grátis
                </button>
              </p>
            )}
            {mode === 'register' && (
              <p className="mt-8 text-center text-sm text-slate-400">
                Já tem conta?{' '}
                <button onClick={() => setMode('login-user')} className="font-semibold text-white hover:text-brand-400 transition-colors">
                  Entrar
                </button>
              </p>
            )}
          </div>
        </motion.div>
      </div>
    </div>
  )
}
