"use client";


import React, { useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { useUser } from '../../components/UserProvider';
import { CheckCircle2, AlertCircle } from 'lucide-react';

const LoginPage = () => {
    const { settings, login } = useUser();
    const siteName = settings?.siteName || "Afrohub";
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [isUnverified, setIsUnverified] = useState(false);
    const [loading, setLoading] = useState(false);
    const [resendLoading, setResendLoading] = useState(false);
    const [resendMessage, setResendMessage] = useState('');
    const [csrfToken, setCsrfToken] = useState('');
    const router = useRouter();
    const searchParams = useSearchParams();
    
    const verified = searchParams.get('verified') === 'true';
    const queryError = searchParams.get('error');
    
    // Fetch CSRF token on mount
    React.useEffect(() => {
        fetch('/api/auth/csrf')
            .then(res => res.json())
            .then(data => setCsrfToken(data.csrfToken))
            .catch(err => console.error('Error fetching CSRF token:', err));
    }, []);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        setError('');
        setIsUnverified(false);
        setResendMessage('');

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

            const data = await res.json();

            if (!res.ok) {
                if (res.status === 403 && data.error?.includes('vérifier')) {
                    setIsUnverified(true);
                }
                throw new Error(data.error || 'Erreur lors de la connexion');
            }

            // Real login with user data from DB
            login(data.user);
            router.push('/dashboard');
        } catch (err: any) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleResendVerification = async () => {
        setResendLoading(true);
        setError('');
        setResendMessage('');

        try {
            const res = await fetch('/api/auth/resend-verification', {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'x-csrf-token': csrfToken
                },
                body: JSON.stringify({ email }),
            });

            const data = await res.json();

            if (!res.ok) {
                throw new Error(data.error || "Erreur lors de l'envoi");
            }

            setResendMessage(data.message);
            setIsUnverified(false); // Hide the resend link after successful send
        } catch (err: any) {
            setError(err.message);
        } finally {
            setResendLoading(false);
        }
    };

    return (
        <div className="min-h-[80vh] flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
            <div className="max-w-md w-full space-y-8">
                <div className="text-center">
                    <div className="mx-auto h-12 w-12 bg-brand-600 rounded-lg flex items-center justify-center text-white font-bold text-2xl">
                        {siteName.charAt(0)}
                    </div>
                    <h2 className="mt-6 text-3xl font-extrabold text-gray-900 font-serif">Connexion à votre espace</h2>
                    <p className="mt-2 text-sm text-gray-600">
                        Ou <Link href="/register" className="font-medium text-brand-600 hover:text-brand-500">créez votre compte entreprise pour 1€</Link>
                    </p>
                </div>

                <div className="mt-8 space-y-6">
                    {verified && (
                        <div className="bg-emerald-50 border-l-4 border-emerald-500 p-4 rounded flex items-center gap-3 text-emerald-700 text-sm">
                            <CheckCircle2 className="w-5 h-5 text-emerald-500 flex-shrink-0" />
                            <p>Votre compte a été vérifié avec succès ! Vous pouvez maintenant vous connecter.</p>
                        </div>
                    )}

                    {resendMessage && (
                        <div className="bg-blue-50 border-l-4 border-blue-500 p-4 rounded flex items-center gap-3 text-blue-700 text-sm">
                            <CheckCircle2 className="w-5 h-5 text-blue-500 flex-shrink-0" />
                            <p>{resendMessage}</p>
                        </div>
                    )}

                    {(error || queryError) && (
                        <div className="bg-red-50 border-l-4 border-red-500 p-4 rounded flex flex-col gap-2 text-red-700 text-sm">
                            <div className="flex items-center gap-3">
                                <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0" />
                                <p>{error || queryError}</p>
                            </div>
                            {isUnverified && (
                                <button
                                    type="button"
                                    onClick={handleResendVerification}
                                    disabled={resendLoading}
                                    className="ml-8 text-left font-bold underline hover:text-red-800 disabled:opacity-50"
                                >
                                    {resendLoading ? 'Envoi en cours...' : "Renvoyer l'email de vérification"}
                                </button>
                            )}
                        </div>
                    )}

                    <form className="space-y-6" onSubmit={handleSubmit} method="POST">
                        <input type="hidden" name="csrf_token" value={csrfToken} />
                    <div className="rounded-md shadow-sm -space-y-px">
                        <div>
                            <input
                                type="email"
                                required
                                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-brand-500 focus:border-brand-500 focus:z-10 sm:text-sm"
                                placeholder="Adresse email"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                            />
                        </div>
                        <div>
                            <input
                                type="password"
                                required
                                className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-brand-500 focus:border-brand-500 focus:z-10 sm:text-sm"
                                placeholder="Mot de passe"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                            />
                        </div>
                    </div>
                    <div className="flex items-center justify-end">
                        <div className="text-sm">
                            <Link href="/forgot-password" title="Réinitialiser votre mot de passe" className="font-medium text-brand-600 hover:text-brand-500">
                                Mot de passe oublié ?
                            </Link>
                        </div>
                    </div>
                    <div>
                        <button 
                            type="submit" 
                            disabled={loading}
                            className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-brand-600 hover:bg-brand-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-500 disabled:opacity-70"
                        >
                            {loading ? 'Connexion...' : 'Se connecter'}
                        </button>
                    </div>
                </form>
                </div>
            </div>
        </div>
    );
};

export default LoginPage;
