import { useState, type FormEvent } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import Navbar from '../components/Navbar'
import { useAuth } from '../contexts/AuthContext'

export default function LoginPage() {
    const { login } = useAuth()
    const navigate = useNavigate()
    const location = useLocation()
    const from =
        (location.state as { from?: { pathname: string } })?.from?.pathname ||
        '/area-do-cliente'

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [error, setError] = useState('')
    const [loading, setLoading] = useState(false)

    async function handleSubmit(e: FormEvent) {
        e.preventDefault()
        setError('')
        setLoading(true)
        try {
            await login({ email, password })
            navigate(from, { replace: true })
        } catch (err: unknown) {
            const axiosErr = err as { response?: { status?: number } }
            if (axiosErr.response?.status === 401) {
                setError('E-mail ou senha incorretos.')
            } else {
                setError('Erro de conexão. Tente novamente.')
            }
        } finally {
            setLoading(false)
        }
    }

    const demoCredentials = [
        { label: 'Admin', email: 'admin@demo.com', password: 'admin1234', admin: true },
        { label: 'Usuário', email: 'usuario@demo.com', password: 'demo1234', admin: false },
    ]

    function fillCredentials(cred: typeof demoCredentials[0]) {
        setEmail(cred.email)
        setPassword(cred.password)
        setError('')
    }

    return (
        <div className="min-h-screen bg-canvas">
            <Navbar />

            <div className="mx-auto flex min-h-[calc(100vh-3.5rem)] w-full max-w-sm items-center justify-center px-4 py-8 pt-20">
                <div className="w-full">
                    <div className="mb-8 text-center">
                        <h1 className="text-2xl font-semibold text-textPrimary">Entrar</h1>
                        <p className="mt-1 text-sm text-textSecondary">Acesse sua conta</p>
                    </div>

                    <form
                        onSubmit={handleSubmit}
                        className="rounded-xl border border-borderSubtle bg-panel p-6 space-y-4"
                    >
                        {error && (
                            <div className="rounded-lg bg-red-500/10 border border-red-500/20 px-3 py-2 text-sm text-red-400">
                                {error}
                            </div>
                        )}

                        <div className="space-y-1">
                            <label className="text-xs font-medium text-textSecondary uppercase tracking-wide">
                                E-mail
                            </label>
                            <input
                                type="email"
                                required
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                className="form-input"
                                placeholder="seu@email.com"
                            />
                        </div>

                        <div className="space-y-1">
                            <label className="text-xs font-medium text-textSecondary uppercase tracking-wide">
                                Senha
                            </label>
                            <input
                                type="password"
                                required
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                className="form-input"
                                placeholder="••••••••"
                            />
                        </div>

                        <button
                            type="submit"
                            disabled={loading}
                            className="w-full rounded-lg bg-brand py-2.5 text-sm font-medium text-white transition hover:bg-accentHover disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                        >
                            {loading && (
                                <span className="h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white" />
                            )}
                            {loading ? 'Entrando...' : 'Entrar'}
                        </button>
                    </form>

                    <p className="mt-4 text-center text-sm text-textTertiary">
                        Não tem conta?{' '}
                        <Link
                            to="/cadastro"
                            className="text-accent hover:text-accentHover transition"
                        >
                            Cadastre-se
                        </Link>
                    </p>

                    {/* Demo credentials */}
                    <div className="mt-6 rounded-xl border border-borderSubtle bg-panel/60 p-4 space-y-3">
                        <p className="text-xs font-semibold text-textTertiary uppercase tracking-wide text-center">
                            Acesso de demonstração
                        </p>
                        {demoCredentials.map((cred) => (
                            <button
                                key={cred.email}
                                type="button"
                                onClick={() => fillCredentials(cred)}
                                className="w-full flex items-center justify-between gap-3 rounded-lg border border-borderSubtle bg-surface hover:bg-panel px-3 py-2.5 transition text-left"
                            >
                                <div className="min-w-0">
                                    <div className="flex items-center gap-2">
                                        <span className="text-xs font-semibold text-textPrimary">{cred.label}</span>
                                        {cred.admin && (
                                            <span className="rounded-full bg-brand/20 text-brand text-[10px] font-semibold px-1.5 py-0.5">
                                                Admin
                                            </span>
                                        )}
                                    </div>
                                    <p className="text-[11px] text-textTertiary truncate">{cred.email}</p>
                                    <p className="text-[11px] text-textTertiary font-mono">{cred.password}</p>
                                </div>
                                <span className="text-xs text-accent shrink-0">Usar →</span>
                            </button>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    )
}
