'use client'
import {useContext, useEffect, useState} from 'react';
import {Mail, Lock, Wifi, CloudUpload, Globe} from "lucide-react";
import SocialForm from "@/app/login/login/SocialForm";
import {useTranslations} from "@/lib/i18n";
import {AlertContext} from "@/context/AlertContext";
import {LangContext, LangContextProps} from "@/context/LangContext";
import {setCookie} from "@/lib/utils/cookies";
import {verifyInput} from "@/lib/utils/validation";
import {apiPostPublic} from "@/lib/api/client";
import * as tauri from '@/lib/tauri';
import Button from "@/components/ui/Button";
import InputField from "@/components/form/InputField";
import TextInput from "@/components/form/TextInput";
import ToggleGroup from "@/components/ui/ToggleGroup";

export default function LoginPage() {
    const t = useTranslations();
    const {errorMessage} = useContext(AlertContext);
    const {lang, setLang} = useContext<LangContextProps>(LangContext);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [showOfflineWarning, setShowOfflineWarning] = useState(false);
    const [resetDone, setResetDone] = useState(false);

    const isDev = process.env.NODE_ENV === 'development';

    useEffect(() => {
        async function checkFirstConnectionAndNetwork() {
            try {
                const token = await tauri.getToken();
                const online = navigator.onLine;
                if (!token && !online) {
                    setShowOfflineWarning(true);
                }
            } catch (error) {
                console.error('Error checking first connection:', error);
            }
        }

        checkFirstConnectionAndNetwork();

        const handleOnline = () => setShowOfflineWarning(false);
        const handleOffline = async () => {
            try {
                const token = await tauri.getToken();
                if (!token) setShowOfflineWarning(true);
            } catch {
                setShowOfflineWarning(true);
            }
        };

        window.addEventListener('online', handleOnline);
        window.addEventListener('offline', handleOffline);
        return () => {
            window.removeEventListener('online', handleOnline);
            window.removeEventListener('offline', handleOffline);
        };
    }, []);

    async function handleSubmit(e: React.FormEvent): Promise<void> {
        e.preventDefault();
        setIsLoading(true);
        errorMessage('');

        if (email.length === 0) {
            errorMessage(t('loginForm.error.emailRequired'));
            setIsLoading(false);
            return;
        }
        if (password.length === 0) {
            errorMessage(t('loginForm.error.passwordRequired'));
            setIsLoading(false);
            return;
        }
        if (email.length < 3) {
            errorMessage(t('loginForm.error.emailLength'));
            setIsLoading(false);
            return;
        }
        if (verifyInput(email) || verifyInput(password)) {
            errorMessage(t('loginForm.error.emailInvalidChars'));
            setIsLoading(false);
            return;
        }

        try {
            const response: string = await apiPostPublic<string>('login', {
                email: email,
                password: password,
            }, lang);
            if (!response) {
                errorMessage(t('loginForm.error.connection'));
                setIsLoading(false);
                return;
            }
            await tauri.setToken(response);
            await tauri.loginSuccess();
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(t('loginForm.error.server'));
            } else {
                errorMessage(t('loginForm.error.unknown'));
            }
        } finally {
            setIsLoading(false);
        }
    }

    return (
        <main className="flex min-h-screen flex-col items-center justify-center bg-tertiary text-text-primary p-4 font-['Lora']">
            <div className="w-full max-w-md px-4 py-10">
                <div className="flex justify-center mb-8">
                    <img src="/logo.png" alt="ERitors" className="object-contain" style={{width: 320, height: 107}}/>
                </div>

                {showOfflineWarning && (
                    <div className="mb-6 bg-warning/10 border border-warning/30 rounded-xl p-4">
                        <div className="flex items-start gap-3">
                            <Wifi className="w-5 h-5 text-warning mt-0.5" strokeWidth={1.75}/>
                            <div>
                                <h3 className="font-semibold text-warning mb-1 flex items-center gap-2">
                                    <CloudUpload className="w-4 h-4" strokeWidth={1.75}/>
                                    {t('loginPage.offlineWarning.title')}
                                </h3>
                                <p className="text-sm text-muted leading-relaxed">
                                    {t('loginPage.offlineWarning.message')}
                                </p>
                            </div>
                        </div>
                    </div>
                )}

                <div className="text-center mb-6">
                    <h1 className="text-2xl sm:text-3xl font-bold mb-2 font-['ADLaM_Display']">{t('loginPage.title')}</h1>
                    <p className="text-muted">{t('loginPage.welcome')}</p>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="bg-darkest-background rounded-xl p-5 space-y-5">
                        <div className="flex justify-end">
                            <ToggleGroup
                                options={[{value: 'fr', label: 'FR'}, {value: 'en', label: 'EN'}]}
                                value={lang}
                                onChange={(value: string) => {
                                    setLang(value as 'fr' | 'en');
                                    setCookie('lang', value, 365);
                                }}
                                icon={Globe}
                                size="sm"
                            />
                        </div>
                        <InputField icon={Mail} fieldName={t('loginForm.fields.email.label')} input={
                            <TextInput value={email} setValue={(e) => setEmail(e.target.value)}
                                       placeholder={t('loginForm.fields.email.placeholder')} size="lg"/>
                        }/>
                        <div>
                            <div className="flex justify-between items-center mb-2">
                                <h3 className="text-text-secondary text-sm font-medium flex items-center gap-2">
                                    <Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
                                    {t('loginForm.fields.password.label')}
                                </h3>
                                <a href="/login/reset-password" className="text-xs text-primary hover:underline">
                                    {t('loginForm.fields.password.forgot')}
                                </a>
                            </div>
                            <input
                                type="password"
                                placeholder={t('loginForm.fields.password.placeholder')}
                                className="input-base px-5 py-3 text-base rounded-xl"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                required
                            />
                        </div>
                    </div>

                    <div className="mt-4">
                        <Button variant="primary" fullWidth size="lg" type="submit" isLoading={isLoading}>
                            {t('loginForm.submit')}
                        </Button>
                    </div>
                </form>

                <div className="relative my-6">
                    <div className="absolute inset-0 flex items-center">
                        <div className="w-full border-t border-secondary"></div>
                    </div>
                    <div className="relative flex justify-center">
                        <span className="px-3 bg-tertiary text-muted text-sm">{t('loginPage.orSocial')}</span>
                    </div>
                </div>

                <div className="flex justify-center gap-3 mb-6">
                    <a href="/login/register"
                       className="flex items-center justify-center w-14 h-14 bg-primary-dark hover:bg-primary text-text-primary rounded-xl transition-colors duration-200">
                        <Mail className="w-6 h-6" strokeWidth={1.75}/>
                    </a>
                    <SocialForm/>
                </div>
            </div>

            {isDev && (
                resetDone
                    ? <span className="mt-6 text-xs text-success">Reset OK</span>
                    : <button onClick={async () => { await tauri.devResetAll(); setResetDone(true); }}
                              className="mt-6 px-4 py-2 text-xs text-error border border-error/30 rounded-lg hover:bg-error/10 transition-colors">
                        DEV: Reset All Data
                    </button>
            )}
        </main>
    );
}
