import React, {Dispatch, SetStateAction, useContext, useState} from "react";
import {AlertContext} from "@/context/AlertContext";
import {Mail, Lock, PenLine, User} from 'lucide-react';
import {useTranslations} from "@/lib/i18n";
import {LangContext, LangContextProps} from "@/context/LangContext";
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 StepOne(
    {
        username,
        email,
        setUsername,
        setEmail,
        handleNextStep
    }: {
        username: string;
        email: string;
        setUsername: Dispatch<SetStateAction<string>>,
        setEmail: Dispatch<SetStateAction<string>>,
        handleNextStep: Function;
    }) {
    const {errorMessage, successMessage} = useContext(AlertContext);
    const [firstName, setFirstName] = useState<string>('');
    const [lastName, setLastName] = useState<string>('');
    const [password, setPassword] = useState<string>('');
    const [repeatPassword, setRepeatPassword] = useState<string>('');
    const [userId, setUserId] = useState<string>('')
    const t = useTranslations();
    const {lang} = useContext<LangContextProps>(LangContext)

    async function handleStep(): Promise<void> {

        if (!firstName || !lastName || !username || !password || !repeatPassword || !email) {
            errorMessage(t('registerStepOne.error.requiredFields'));
            return;
        }
        if (firstName.length < 2 || firstName.length > 50) {
            errorMessage(t('registerStepOne.error.firstNameLength'));
            return;
        }
        if (lastName.length < 2 || lastName.length > 50) {
            errorMessage(t('registerStepOne.error.lastNameLength'));
            return;
        }
        if (username.length < 3 || username.length > 50) {
            errorMessage(t('registerStepOne.error.usernameLength'));
            return;
        }
        if (verifyInput(firstName) || verifyInput(lastName) || verifyInput(username) || verifyInput(password) || verifyInput(repeatPassword) || verifyInput(email)) {
            errorMessage(t('registerStepOne.error.invalidInput'));
            return;
        }

        if (password != repeatPassword) {
            errorMessage(t('registerStepOne.error.passwordMismatch'));
            return;
        }
        try {
            const response: string = await apiPostPublic<string>(`register/pre`, {
                firstName,
                lastName,
                username,
                email,
                password,
                retypePass: repeatPassword
            }, lang);
            if (!response) {
                errorMessage(t('registerStepOne.error.preRegister'));
                return;
            }
            setUserId(response);
            successMessage(t('registerStepOne.success.preRegister'));
            handleNextStep();
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t('registerStepOne.error.unknown'));
            }
        }
    }

    return (
        <form className="space-y-4">
            <InputField icon={PenLine} fieldName={t('registerStepOne.fields.firstName.label')} input={
                <TextInput value={firstName} setValue={(e) => setFirstName(e.target.value)}
                           placeholder={t('registerStepOne.fields.firstName.placeholder')}/>
            }/>

            <InputField icon={PenLine} fieldName={t('registerStepOne.fields.lastName.label')} input={
                <TextInput value={lastName} setValue={(e) => setLastName(e.target.value)}
                           placeholder={t('registerStepOne.fields.lastName.placeholder')}/>
            }/>

            <div>
                <InputField icon={User} fieldName={t('registerStepOne.fields.username.label')} input={
                    <TextInput value={username} setValue={(e) => setUsername(e.target.value)}
                               placeholder={t('registerStepOne.fields.username.placeholder')}/>
                }/>
                <p className="text-xs text-muted mt-1">{t('registerStepOne.fields.username.note')}</p>
            </div>

            <InputField icon={Mail} fieldName={t('registerStepOne.fields.email.label')} input={
                <TextInput value={email} setValue={(e) => setEmail(e.target.value)}
                           placeholder={t('registerStepOne.fields.email.placeholder')}/>
            }/>

            <div>
                <h3 className="text-text-secondary text-sm font-medium flex items-center gap-2 mb-2">
                    <Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
                    {t('registerStepOne.fields.password.label')}
                </h3>
                <input
                    type="password"
                    placeholder={t('registerStepOne.fields.password.placeholder')}
                    className="input-base"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                />
            </div>

            <div>
                <h3 className="text-text-secondary text-sm font-medium flex items-center gap-2 mb-2">
                    <Lock className="text-primary w-5 h-5" strokeWidth={1.75}/>
                    {t('registerStepOne.fields.repeatPassword.label')}
                </h3>
                <input
                    type="password"
                    placeholder={t('registerStepOne.fields.repeatPassword.placeholder')}
                    className="input-base"
                    value={repeatPassword}
                    onChange={(e) => setRepeatPassword(e.target.value)}
                    required
                />
            </div>

            <Button variant="primary" fullWidth size="lg" onClick={() => handleStep()}>
                {t('registerStepOne.next')}
            </Button>
        </form>
    )
}
