"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Button, Input, Checkbox } from "@/components/ui";
import { saveAuth, isAuthenticated } from '@/lib/auth';
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') {
            setIsSuperAdmin(true);
            setGradientVariables(DEFAULT_GRADIENT);

            if (isAuthenticated()) {
                const userData = localStorage.getItem('user');
                if (userData) {
                    const user = JSON.parse(userData);
                    if (user.role === 'SUPERADMIN') {
                        window.location.href = '/superadmin';
                    } else {
                        localStorage.removeItem('token');
                        localStorage.removeItem('user');
                    }
                }
            }
        }
    }, []);

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

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

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

        if (!formData.password) {
            console.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);
            console.log('Login realizado com sucesso! Redirecionando...');

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

    return (
        <>
            <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>
                        </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">
                                aggios
                            </h1>
                            <p className="text-xl opacity-90 mb-8">
                                Gerencie todas as agências em um só lugar
                            </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>
        </>
    );
}
