import {useContext, useState} from "react";
import {Mail, Lock} from "lucide-react";
import {AlertContext} from "@/context/AlertContext";
import {useTranslations} from "@/lib/i18n";
import {LangContext, LangContextProps} from "@/context/LangContext";
import * as tauri from '@/lib/tauri';
import {verifyInput} from "@/lib/utils/validation";
import {apiPostPublic} from "@/lib/api/client";
import Button from "@/components/ui/Button";
import InputField from "@/components/form/InputField";
import TextInput from "@/components/form/TextInput";

export default function LoginForm() {
    const {errorMessage} = useContext(AlertContext);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    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'));
            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 (
        <form onSubmit={handleSubmit} className="space-y-5">
            <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>

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