"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Button, Input, Checkbox } from "@/components/ui";
import toast, { Toaster } from 'react-hot-toast';
import { saveAuth, isAuthenticated, getToken, clearAuth } from '@/lib/auth';
import { API_ENDPOINTS } from '@/lib/api';
import dynamic from 'next/dynamic';

const ThemeToggle = dynamic(() => import('@/components/ThemeToggle'), { ssr: false });

const DEFAULT_GRADIENT = 'linear-gradient(135deg, #ff3a05, #ff0080)';

const setGradientVariables = (gradient: string) => {
    document.documentElement.style.setProperty('--gradient-primary', gradient);
    document.documentElement.style.setProperty('--gradient', gradient);
    document.documentElement.style.setProperty('--gradient-text', gradient.replace('90deg', 'to right'));
    document.documentElement.style.setProperty('--color-gradient-brand', gradient.replace('90deg', 'to right'));
};

export default function LoginPage() {
    const [isLoading, setIsLoading] = useState(false);
    const [isSuperAdmin, setIsSuperAdmin] = useState(false);
    const [subdomain, setSubdomain] = useState<string>('');
    const [formData, setFormData] = useState({
        email: "",
        password: "",
        rememberMe: false,
    });

    useEffect(() => {
        if (typeof window !== 'undefined') {
            const hostname = window.location.hostname;
            const sub = hostname.split('.')[0];
            const superAdmin = sub === 'dash';
            setSubdomain(sub);
            setIsSuperAdmin(superAdmin);

            // Aplicar tema: dash sempre padrão; tenants aplicam o salvo ou vindo via query param
            const searchParams = new URLSearchParams(window.location.search);
            const themeParam = searchParams.get('theme');

            if (superAdmin) {
                setGradientVariables(DEFAULT_GRADIENT);
            } else {
                const stored = localStorage.getItem(`agency-theme:${sub}`);
                const gradient = themeParam || stored || DEFAULT_GRADIENT;
                setGradientVariables(gradient);

                if (themeParam) {
                    localStorage.setItem(`agency-theme:${sub}`, gradient);
                }
            }

            if (isAuthenticated()) {
                // Validar token antes de redirecionar para evitar loops
                const token = getToken();
                fetch(API_ENDPOINTS.me, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                    .then(res => {
                        if (res.ok) {
                            const target = superAdmin ? '/superadmin' : '/dashboard';
                            window.location.href = target;
                        } else {
                            // Token inválido ou expirado
                            clearAuth();
                        }
                    })
                    .catch((err) => {
                        console.error('Erro ao validar sessão:', err);
                        // Em caso de erro de rede, não redireciona nem limpa, deixa o usuário tentar logar
                    });
            }
        }
    }, []);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!formData.email) {
            toast.error('Por favor, insira seu email');
            return;
        }

        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
            toast.error('Por favor, insira um email válido');
            return;
        }

        if (!formData.password) {
            toast.error('Por favor, insira sua senha');
            return;
        }

        setIsLoading(true);

        try {
            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    email: formData.email,
                    password: formData.password,
                }),
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.message || 'Credenciais inválidas');
            }

            const data = await response.json();

            saveAuth(data.token, data.user);

            console.log('Login successful:', data.user);

            toast.success('Login realizado com sucesso! Redirecionando...');

            setTimeout(() => {
                const target = isSuperAdmin ? '/superadmin' : '/dashboard';
                window.location.href = target;
            }, 1000);
        } catch (error: any) {
            toast.error(error.message || 'Erro ao fazer login. Verifique suas credenciais.');
            setIsLoading(false);
        }
    };

    return (
        <>
            <Toaster
                position="top-center"
                toastOptions={{
                    duration: 5000,
                    style: {
                        background: '#FFFFFF',
                        color: '#000000',
                        padding: '16px',
                        borderRadius: '8px',
                        border: '1px solid #E5E5E5',
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                    },
                    error: {
                        icon: '⚠️',
                        style: {
                            background: '#ef4444',
                            color: '#FFFFFF',
                            border: 'none',
                        },
                    },
                    success: {
                        icon: '✓',
                        style: {
                            background: '#10B981',
                            color: '#FFFFFF',
                            border: 'none',
                        },
                    },
                }}
            />
            <div className="flex min-h-screen">
                {/* Lado Esquerdo - Formulário */}
                <div className="w-full lg:w-1/2 flex items-center justify-center px-6 sm:px-12 py-12">
                    <div className="w-full max-w-md">
                        {/* Logo mobile */}
                        <div className="lg:hidden text-center mb-8">
                            <div className="inline-block px-6 py-3 rounded-2xl" style={{ background: 'var(--gradient-primary)' }}>
                                <h1 className="text-3xl font-bold text-white">
                                    {isSuperAdmin ? 'aggios' : subdomain}
                                </h1>
                            </div>
                        </div>

                        {/* Theme Toggle */}
                        <div className="flex justify-end mb-4">
                            <ThemeToggle />
                        </div>

                        {/* Header */}
                        <div className="mb-8">
                            <h2 className="text-[28px] font-bold text-[#000000] dark:text-white">
                                {isSuperAdmin ? 'Painel Administrativo' : 'Bem-vindo de volta'}
                            </h2>
                            <p className="text-[14px] text-[#7D7D7D] dark:text-gray-400 mt-2">
                                {isSuperAdmin
                                    ? 'Acesso exclusivo para administradores Aggios'
                                    : 'Entre com suas credenciais para acessar o painel'
                                }
                            </p>
                        </div>

                        {/* Form */}
                        <form onSubmit={handleSubmit} className="space-y-5">
                            <Input
                                label="Email"
                                type="email"
                                placeholder="seu@email.com"
                                leftIcon="ri-mail-line"
                                value={formData.email}
                                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                                required
                            />

                            <Input
                                label="Senha"
                                type="password"
                                placeholder="Digite sua senha"
                                leftIcon="ri-lock-line"
                                value={formData.password}
                                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                required
                            />

                            <div className="flex items-center justify-between">
                                <Checkbox
                                    id="rememberMe"
                                    label="Lembrar de mim"
                                    checked={formData.rememberMe}
                                    onChange={(e) => setFormData({ ...formData, rememberMe: e.target.checked })}
                                />
                                <Link
                                    href="/recuperar-senha"
                                    className="text-[14px] font-medium hover:opacity-80 transition-opacity"
                                    style={{ background: 'var(--gradient-primary)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}
                                >
                                    Esqueceu a senha?
                                </Link>
                            </div>

                            <Button
                                type="submit"
                                variant="primary"
                                size="lg"
                                className="w-full"
                                disabled={isLoading}
                            >
                                {isLoading ? 'Entrando...' : 'Entrar'}
                            </Button>

                            {/* Link para cadastro - apenas para agências */}
                            {!isSuperAdmin && (
                                <p className="text-center text-[14px] text-[#7D7D7D] dark:text-gray-400">
                                    Ainda não tem conta?{' '}
                                    <a
                                        href="http://dash.localhost/cadastro"
                                        className="font-medium hover:opacity-80 transition-opacity"
                                        style={{ background: 'var(--gradient-primary)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}
                                    >
                                        Cadastre sua agência
                                    </a>
                                </p>
                            )}
                        </form>
                    </div>
                </div>

                {/* Lado Direito - Branding */}
                <div className="hidden lg:flex lg:w-1/2 relative overflow-hidden" style={{ background: 'var(--gradient-primary)' }}>
                    <div className="absolute inset-0 flex flex-col items-center justify-center p-12 text-white">
                        <div className="max-w-md text-center">
                            <h1 className="text-5xl font-bold mb-6">
                                {isSuperAdmin ? 'aggios' : subdomain}
                            </h1>
                            <p className="text-xl opacity-90 mb-8">
                                {isSuperAdmin
                                    ? 'Gerencie todas as agências em um só lugar'
                                    : 'Gerencie seus clientes com eficiência'
                                }
                            </p>
                            <div className="grid grid-cols-2 gap-6 text-left">
                                <div>
                                    <i className="ri-shield-check-line text-3xl mb-2"></i>
                                    <h3 className="font-semibold mb-1">Seguro</h3>
                                    <p className="text-sm opacity-80">Proteção de dados</p>
                                </div>
                                <div>
                                    <i className="ri-speed-line text-3xl mb-2"></i>
                                    <h3 className="font-semibold mb-1">Rápido</h3>
                                    <p className="text-sm opacity-80">Performance otimizada</p>
                                </div>
                                <div>
                                    <i className="ri-team-line text-3xl mb-2"></i>
                                    <h3 className="font-semibold mb-1">Colaborativo</h3>
                                    <p className="text-sm opacity-80">Trabalho em equipe</p>
                                </div>
                                <div>
                                    <i className="ri-line-chart-line text-3xl mb-2"></i>
                                    <h3 className="font-semibold mb-1">Insights</h3>
                                    <p className="text-sm opacity-80">Relatórios detalhados</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}
