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

export default function Register() {
    const t = useTranslations();
    const {errorMessage, successMessage} = useContext(AlertContext);
    const {lang} = useContext<LangContextProps>(LangContext);

    const [step, setStep] = useState<number>(1);
    const [username, setUsername] = useState<string>('');
    const [email, setEmail] = useState<string>('');
    const [password, setPassword] = useState<string>('');
    const [repeatPassword, setRepeatPassword] = useState<string>('');
    const [verifyCode, setVerifyCode] = useState<string>('');
    const [isConfirmed, setIsConfirmed] = useState<boolean>(false);

    async function handleStepOne(): Promise<void> {
        if (!username || !password || !repeatPassword || !email) {
            errorMessage(t('registerStepOne.error.requiredFields'));
            return;
        }
        if (username.length < 3 || username.length > 50) {
            errorMessage(t('registerStepOne.error.usernameLength'));
            return;
        }
        if (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', {
                username, email, password, retypePass: repeatPassword
            }, lang);
            if (!response) {
                errorMessage(t('registerStepOne.error.preRegister'));
                return;
            }
            successMessage(t('registerStepOne.success.preRegister'));
            setStep(2);
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t('registerStepOne.error.unknown'));
            }
        }
    }

    async function handleVerifyCode(): Promise<void> {
        if (verifyCode === '') {
            errorMessage(t('registerStepTwo.error.codeIncorrect'));
            return;
        }
        try {
            const response: boolean = await apiPostPublic<boolean>('register/verify-code', {
                verifyCode, email,
            }, lang);
            if (!response) {
                errorMessage(t('registerStepTwo.error.codeIncorrect'));
                return;
            }
            setIsConfirmed(true);
            successMessage(t('registerStepTwo.success.verified'));
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t('registerStepTwo.error.unknown'));
            }
        }
    }

    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>

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

                {step === 1 && !isConfirmed && (
                    <>
                        <div className="overflow-hidden rounded-xl mb-4">
                            <div className="flex items-center">
                                <div className={`flex-grow h-2 ${step >= 1 ? 'bg-primary' : 'bg-secondary'}`}></div>
                                <div className="w-1 bg-tertiary"></div>
                                <div className={`flex-grow h-2 ${step >= 2 ? 'bg-primary' : 'bg-secondary'}`}></div>
                            </div>
                            <div className="bg-darkest-background p-5 space-y-4">
                                <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>
                            </div>
                        </div>

                        <div className="space-y-3">
                            <Button variant="primary" fullWidth size="lg" onClick={handleStepOne}>
                                {t('registerStepOne.next')}
                            </Button>
                            <a href="/login/login" className="block w-full">
                                <Button variant="secondary" fullWidth icon={ArrowLeft}>
                                    {t('registerPage.backToLogin')}
                                </Button>
                            </a>
                        </div>
                    </>
                )}

                {step === 2 && !isConfirmed && (
                    <>
                        <div className="overflow-hidden rounded-xl mb-4">
                            <div className="flex items-center">
                                <div className="flex-grow h-2 bg-primary"></div>
                                <div className="w-1 bg-tertiary"></div>
                                <div className="flex-grow h-2 bg-primary"></div>
                            </div>
                            <div className="bg-darkest-background p-5 space-y-4">
                                <div className="text-center">
                                    <p className="text-muted">{t('registerStepTwo.instructions.sent')}</p>
                                    <p className="text-muted text-sm mt-2">{t('registerStepTwo.instructions.checkInbox')}</p>
                                </div>
                                <InputField icon={KeyRound} fieldName={t('registerStepTwo.fields.code.label')} input={
                                    <TextInput value={verifyCode} setValue={(e) => setVerifyCode(e.target.value)}
                                               placeholder={t('registerStepTwo.fields.code.placeholder')}/>
                                }/>
                            </div>
                        </div>

                        <div className="space-y-3">
                            <Button variant="primary" fullWidth size="lg" onClick={handleVerifyCode}>
                                {t('registerStepTwo.verify')}
                            </Button>
                            <Button variant="secondary" fullWidth onClick={() => setStep(1)}>
                                {t('registerStepTwo.back')}
                            </Button>
                        </div>
                    </>
                )}

                {isConfirmed && (
                    <>
                        <div className="bg-darkest-background rounded-xl p-5 mb-4">
                            <div className="p-4 bg-success/20 border border-success rounded-xl">
                                <p className="text-center text-text-primary">{t('registerStepTwo.confirmed')}</p>
                            </div>
                        </div>

                        <Link href="/login" className="block w-full">
                            <Button variant="primary" fullWidth size="lg">
                                {t('registerStepTwo.start')}
                            </Button>
                        </Link>
                    </>
                )}
            </div>
        </main>
    );
}
