"use client";

import { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useAuth } from '@/context/AuthContext';
import { FcGoogle } from 'react-icons/fc';
import '@/styles/Auth.css';

export default function LoginPage() {
    const router = useRouter();
    const { login, isAuthenticated, loading: authLoading } = useAuth();
    const [formData, setFormData] = useState({
        emailOrUsername: '',
        password: '',
        rememberMe: false,
    });
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);
    const [twoFactorRequired, setTwoFactorRequired] = useState(false);
    const [twoFactorUserId, setTwoFactorUserId] = useState<number | null>(null);
    const [twoFactorCode, setTwoFactorCode] = useState('');
    const [successMessage, setSuccessMessage] = useState('');

    useEffect(() => {
        // Load remembered credentials ONCE on mount
        const savedEmail = localStorage.getItem('remembered_email');
        if (savedEmail) {
            setFormData(prev => ({ ...prev, emailOrUsername: savedEmail, rememberMe: true }));
        }
    }, []);

    const processingGoogleAuth = useRef(false);

    useEffect(() => {
        if (!authLoading && isAuthenticated) {
            router.push('/me');
            return;
        }

        if (processingGoogleAuth.current) return;

        // Check for verification query params
        const params = new URLSearchParams(window.location.search);

        // Handle successful Google Redirect
        const token = params.get('token');
        const userData = params.get('user');

        if (token && userData) {
            processingGoogleAuth.current = true;
            try {
                login(token, JSON.parse(userData), true);
                // Clear URL parameters to prevent re-processing on refresh/back
                window.history.replaceState({}, document.title, window.location.pathname);
                router.push('/me');
                return;
            } catch (e) {
                console.error("Failed to parse Google user data", e);
                processingGoogleAuth.current = false;
            }
        }

        if (params.get('verified') === 'true') {
            setSuccessMessage('Din e-postadress har blivit verifierad! Du kan nu logga in.');
        } else if (params.get('error') === 'InvalidToken') {
            setError('Verifieringslänken är ogiltig eller har gått ut.');
        } else if (params.get('error') === 'GoogleAuthFailed') {
            setError('Google-inloggning misslyckades. Försök igen.');
        }
    }, [isAuthenticated, authLoading, router, login]);

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

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

            const data = await res.json();

            if (!res.ok) {
                throw new Error(data.error || 'Inloggningen misslyckades');
            }

            if (data.twoFactorRequired) {
                setTwoFactorRequired(true);
                setTwoFactorUserId(data.userId);
                setLoading(false);
                return;
            }

            // The actual saving of remembered email is now handled by the checkbox onChange
            // or here if we want to be 100% sure on success
            if (formData.rememberMe) {
                localStorage.setItem('remembered_email', formData.emailOrUsername);
            } else {
                localStorage.removeItem('remembered_email');
            }

            // Update global auth state
            login(data.token, data.user, formData.rememberMe);
            router.push('/me');
        } catch (err: unknown) {
            if (err instanceof Error) {
                setError(err.message);
            } else {
                setError('Ett oväntat fel uppstod');
            }
            setLoading(false);
        }
    };

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

        try {
            const res = await fetch('/api/auth/2fa/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    userId: twoFactorUserId,
                    code: twoFactorCode,
                }),
            });

            const data = await res.json();

            if (!res.ok) {
                throw new Error(data.error || 'Verifieringen misslyckades');
            }

            if (formData.rememberMe) {
                localStorage.setItem('remembered_email', formData.emailOrUsername);
            } else {
                localStorage.removeItem('remembered_email');
            }

            login(data.token, data.user, formData.rememberMe);
            router.push('/me');
        } catch (err: unknown) {
            if (err instanceof Error) {
                setError(err.message);
            } else {
                setError('Ett oväntat fel uppstod');
            }
            setLoading(false);
        }
    };

    const handleGoogleLogin = async () => {
        try {
            const res = await fetch('/api/auth/google/url');
            const data = await res.json();
            if (data.url) {
                window.location.href = data.url;
            } else {
                setError('Kunde inte starta Google-inloggning');
            }
        } catch {
            setError('Ett fel uppstod vid Google-inloggning');
        }
    };

    if (authLoading || isAuthenticated) {
        return null;
    }

    return (
        <div className="auth-page-container">
            <div className="profile-card card-sm">
                <h2 className="auth-title">{twoFactorRequired ? '2FA Verifiering' : 'LOGGA IN'}</h2>

                {successMessage && (
                    <div className="auth-success">
                        {successMessage}
                    </div>
                )}

                <p className="auth-subtitle">
                    {twoFactorRequired
                        ? 'Ange koden från din autentiseringsapp'
                        : 'Logga in på ditt konto för att fortsätta'
                    }
                </p>

                {!twoFactorRequired ? (
                    <form className="auth-form" onSubmit={handleSubmit}>
                        <div className="form-group">
                            <label className="form-label" htmlFor="email">
                                E-post eller Användarnamn
                            </label>
                            <input
                                id="email"
                                name="email"
                                type="text"
                                autoComplete="username"
                                required
                                className="form-input"
                                placeholder="Ange din e-post eller användarnamn"
                                value={formData.emailOrUsername}
                                onChange={(e) => setFormData({ ...formData, emailOrUsername: e.target.value })}
                            />
                        </div>

                        <div className="form-group">
                            <label className="form-label" htmlFor="password">
                                Lösenord
                            </label>
                            <input
                                id="password"
                                name="password"
                                type="password"
                                autoComplete="current-password"
                                required
                                className="form-input"
                                placeholder="Ange ditt lösenord"
                                value={formData.password}
                                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                            />
                        </div>

                        <div className="form-checkbox-group">
                            <input
                                id="rememberMe"
                                type="checkbox"
                                className="form-checkbox"
                                checked={formData.rememberMe}
                                onChange={(e) => {
                                    const checked = e.target.checked;
                                    setFormData(prev => ({ ...prev, rememberMe: checked }));

                                    // If manually unticking, clear it immediately so it doesn't return on refresh
                                    if (!checked) {
                                        localStorage.removeItem('remembered_email');
                                    }
                                }}
                            />
                            <label htmlFor="rememberMe">Kom ihåg mig</label>
                        </div>

                        {error && (
                            <div className="auth-error">
                                {error}
                            </div>
                        )}

                        <div className="auth-button-container mt-4">
                            <button
                                type="submit"
                                disabled={loading}
                                className="auth-button"
                            >
                                {loading ? 'Loggar in...' : 'Logga in'}
                            </button>

                            <button
                                type="button"
                                onClick={handleGoogleLogin}
                                className="auth-button google"
                            >
                                <FcGoogle size={20} />
                                Fortsätt med Google
                            </button>

                            <div className="auth-divider">ELLER</div>

                            <Link href="/register" className="auth-button secondary">
                                Registrera
                            </Link>
                        </div>

                        <div className="text-center mt-6">
                            <Link href="/forgot" className="auth-link text-xs">
                                Glömt Lösenord?
                            </Link>
                        </div>
                    </form>
                ) : (
                    <form className="auth-form" onSubmit={handle2FAVerify}>
                        <div className="form-group">
                            <label className="form-label">6-siffrig kod</label>
                            <input
                                id="2fa-code"
                                type="text"
                                required
                                className="form-input"
                                placeholder="000000"
                                maxLength={6}
                                value={twoFactorCode}
                                onChange={(e) => setTwoFactorCode(e.target.value)}
                            />
                        </div>

                        {error && (
                            <div className="auth-error">
                                {error}
                            </div>
                        )}

                        <button
                            type="submit"
                            disabled={loading}
                            className="auth-button"
                        >
                            {loading ? 'Verifierar...' : 'Verifiera & Logga in'}
                        </button>

                        <button
                            type="button"
                            className="auth-link btn-link-raw block mx-auto mt-4"
                            onClick={() => setTwoFactorRequired(false)}
                        >
                            Tillbaka till inloggning
                        </button>
                    </form>
                )}
            </div>
        </div>
    );
}
