import {useContext, useState} from "react";
import System from "@/lib/models/System";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faEnvelope, faLock} from "@fortawesome/free-solid-svg-icons";
import {SessionContext, SessionContextProps} from "@/context/SessionContext";
import {AlertContext} from "@/context/AlertContext";
import {useTranslations} from "next-intl";
import {LangContext, LangContextProps} from "@/context/LangContext";

export default function LoginForm() {
    const {errorMessage} = useContext(AlertContext);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const {setSession} = useContext<SessionContextProps>(SessionContext);
    const t = useTranslations();
    const {lang} = useContext<LangContextProps>(LangContext)
    
    async function handleSubmit(e: React.FormEvent): Promise<void> {
        e.preventDefault();
        setIsLoading(true);
        errorMessage('');
        
        if (email.length === 0) {
            errorMessage(t('loginForm.error.emailRequired'));
            return;
        }
        if (password.length === 0) {
            errorMessage(t('loginForm.error.passwordRequired'));
            return;
        }
        if (email.length < 3) {
            errorMessage(t('loginForm.error.emailLength'));
            return;
        }
        
        if (System.verifyInput(email) || System.verifyInput(password)) {
            errorMessage(t('loginForm.error.emailInvalidChars'));
            return;
        }
        try {
            const response: string = await System.postToServer<string>('login', {
                email: email,
                password: password,
            }, lang)
            if (!response) {
                errorMessage(t('loginForm.error.connection'));
                setIsLoading(false);
                return;
            }
            // Stocker le token dans electron-store via IPC
            if (window.electron) {
                await window.electron.setToken(response);
                window.electron.loginSuccess(response);
            } else {
                // Fallback pour le mode dev web
                System.setCookie('token', response, 30);
                const token: string | null = System.getCookie('token');
                if (!token) {
                    errorMessage(t('loginForm.error.connection'));
                    setIsLoading(false);
                    return;
                }
                setSession({isConnected: true, user: null, accessToken: token})
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(t('loginForm.error.server'));
            } else {
                errorMessage(t('loginForm.error.unknown'));
            }
        } finally {
            setIsLoading(false);
        }
    }
    
    return (
        <form onSubmit={handleSubmit}>
            <div className="mb-5">
                <label htmlFor="email" className="block text-sm font-medium mb-1 text-muted">
                    {t('loginForm.fields.email.label')}
                </label>
                <div className="relative">
                    <FontAwesomeIcon icon={faEnvelope}
                                     className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
                    <input
                        type="email"
                        id="email"
                        placeholder={t('loginForm.fields.email.placeholder')}
                        className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        required
                    />
                </div>
            </div>
            
            <div className="mb-5">
                <div className="flex justify-between items-center mb-1">
                    <label htmlFor="password" className="block text-sm font-medium text-muted">
                        {t('loginForm.fields.password.label')}
                    </label>
                    <a href="/login/reset-password" className="text-xs text-primary hover:underline">
                        {t('loginForm.fields.password.forgot')}
                    </a>
                </div>
                <div className="relative">
                    <FontAwesomeIcon icon={faLock}
                                     className="absolute left-4 top-1/2 transform -translate-y-1/2 text-muted w-5 h-5"/>
                    <input
                        type="password"
                        id="password"
                        placeholder={t('loginForm.fields.password.placeholder')}
                        className="w-full pl-12 pr-4 py-4 bg-secondary border border-gray-dark rounded-xl focus:outline-none focus:border-primary transition-colors"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                    />
                </div>
            </div>
            
            <button
                type="submit"
                className={`w-full py-4 mb-4 bg-gradient-to-r from-primary to-info text-textPrimary font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/20 transition-all ${isLoading ? 'opacity-75 cursor-not-allowed' : ''}`}
                disabled={isLoading}
            >
                {isLoading ? t('loginForm.loading') : t('loginForm.submit')}
            </button>
        </form>
    )
}
