'use client'
import {useContext, useState} from "react";
import {Mail, KeyRound, Lock, ArrowLeft} from 'lucide-react';
import {QueryDataResponse} from "@/shared/interface";
import {AlertContext} from "@/context/AlertContext";
import {useTranslations} from "@/lib/i18n";
import {LangContext, LangContextProps} from "@/context/LangContext";
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 ForgetPasswordPage() {
    const [step, setStep] = useState(1);
    const [email, setEmail] = useState('');
    const [verificationCode, setVerificationCode] = useState('');
    const [isConfirmed, setIsConfirmed] = useState(false);
    const [newPassword, setNewPassword] = useState<string>('');
    const {errorMessage, successMessage} = useContext(AlertContext);
    const t = useTranslations();
    const {lang} = useContext<LangContextProps>(LangContext)

    async function handleEmailCheck(): Promise<void> {
        if (!email) {
            errorMessage(t('resetPassword.error.emailInvalid'));
            return;
        }
        const emailRegEx = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegEx.test(email)) {
            errorMessage(t('resetPassword.error.emailFormat'));
            return;
        }
        try {
            const response: QueryDataResponse<null> = await apiPostPublic<QueryDataResponse<null>>('user/email-check', {email}, lang);
            if (response.valid) {
                successMessage(response.message ?? '');
                setStep(2);
            } else {
                errorMessage(response.message ?? '');
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(t('resetPassword.error.emailServer'));
            } else {
                errorMessage(t('resetPassword.error.emailUnknown'));
            }
        }
    }

    async function handleConfirm(): Promise<void> {
        try {
            const response: QueryDataResponse<null> = await apiPostPublic<QueryDataResponse<null>>('user/verify-code', {
                verifyCode: verificationCode, email,
            }, lang);
            if (response.valid) {
                successMessage(response.message ?? '');
                setIsConfirmed(true);
            } else {
                errorMessage(response.message ?? '');
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(t('resetPassword.error.codeServer'));
            } else {
                errorMessage(t('resetPassword.error.codeUnknown'));
            }
        }
    }

    async function handleNewPassword(): Promise<void> {
        try {
            const response: QueryDataResponse<null> = await apiPostPublic<QueryDataResponse<null>>('password/reset', {
                email, newPassword, code: verificationCode
            }, lang);
            if (response.valid) {
                successMessage(response.message ?? '');
                setStep(3);
            } else {
                errorMessage(response.message ?? '');
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(t('resetPassword.error.passwordServer'));
            } else {
                errorMessage(t('resetPassword.error.passwordUnknown'));
            }
        }
    }

    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('resetPassword.title')}</h1>
                    <p className="text-muted text-sm">{t('resetPassword.subtitle')}</p>
                </div>

                {step < 3 && (
                    <>
                        <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 className="w-1 bg-tertiary"></div>
                                <div className={`flex-grow h-2 ${step >= 3 ? 'bg-primary' : 'bg-secondary'}`}></div>
                            </div>
                            <div className="bg-darkest-background p-5 space-y-4">
                                {step === 1 && (
                                    <InputField icon={Mail} fieldName={t('resetPassword.fields.email.label')} input={
                                        <TextInput value={email} setValue={(e) => setEmail(e.target.value)}
                                                   placeholder={t('resetPassword.fields.email.placeholder')}/>
                                    }/>
                                )}
                                {step === 2 && (
                                    <>
                                        <InputField icon={KeyRound} fieldName={t('resetPassword.fields.code.label')} input={
                                            <TextInput value={verificationCode}
                                                       setValue={(e) => setVerificationCode(e.target.value)}
                                                       placeholder={t('resetPassword.fields.code.placeholder')}
                                                       disabled={isConfirmed}/>
                                        }/>
                                        {isConfirmed && (
                                            <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('resetPassword.fields.newPassword.label')}
                                                </h3>
                                                <input type="password"
                                                       placeholder={t('resetPassword.fields.newPassword.placeholder')}
                                                       className="input-base" value={newPassword}
                                                       onChange={(e) => setNewPassword(e.target.value)} required/>
                                            </div>
                                        )}
                                    </>
                                )}
                            </div>
                        </div>

                        <div className="space-y-3">
                            {step === 1 && (
                                <>
                                    <Button variant="primary" fullWidth size="lg" onClick={handleEmailCheck}>
                                        {t('resetPassword.verify')}
                                    </Button>
                                    <a href="/login/login" className="block w-full">
                                        <Button variant="secondary" fullWidth icon={ArrowLeft}>
                                            {t('resetPassword.backToLogin')}
                                        </Button>
                                    </a>
                                </>
                            )}
                            {step === 2 && (
                                <>
                                    <Button variant="primary" fullWidth size="lg"
                                            onClick={isConfirmed ? handleNewPassword : handleConfirm}>
                                        {isConfirmed ? t('resetPassword.changePassword') : t('resetPassword.confirm')}
                                    </Button>
                                    <Button variant="secondary" fullWidth onClick={() => setStep(1)}>
                                        {t('resetPassword.back')}
                                    </Button>
                                </>
                            )}
                        </div>
                    </>
                )}

                {step === 3 && (
                    <>
                        <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('resetPassword.success')}</p>
                            </div>
                        </div>

                        <a href="/login/login" className="block w-full">
                            <Button variant="primary" fullWidth size="lg">
                                {t('resetPassword.goToLogin')}
                            </Button>
                        </a>
                    </>
                )}
            </div>
        </main>
    )
}
