import { Form, Head, setLayoutProps } from '@inertiajs/react';
import { motion } from 'framer-motion';
import { REGEXP_ONLY_DIGITS } from 'input-otp';
import { useMemo, useState } from 'react';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    InputOTP,
    InputOTPGroup,
    InputOTPSlot,
} from '@/components/ui/input-otp';
import { OTP_MAX_LENGTH } from '@/hooks/use-two-factor-auth';
import { store } from '@/routes/two-factor/login';

const itemVariants = {
    hidden: { opacity: 0, y: 15 },
    visible: { 
        opacity: 1, 
        y: 0, 
        transition: { duration: 0.5, ease: [0.22, 1, 0.36, 1] } 
    }
};

export default function TwoFactorChallenge() {
    const [showRecoveryInput, setShowRecoveryInput] = useState<boolean>(false);
    const [code, setCode] = useState<string>('');

    const authConfigContent = useMemo<{
        title: string;
        description: string;
        toggleText: string;
    }>(() => {
        if (showRecoveryInput) {
            return {
                title: 'Code de récupération',
                description:
                    'Confirmez l’accès à votre compte en saisissant l’un de vos codes de récupération d’urgence.',
                toggleText: 'vous connecter avec un code d’authentification',
            };
        }

        return {
            title: 'Code d’authentification',
            description:
                'Saisissez le code fourni par votre application d’authentification.',
            toggleText: 'vous connecter avec un code de récupération',
        };
    }, [showRecoveryInput]);

    setLayoutProps({
        title: authConfigContent.title,
        description: authConfigContent.description,
    });

    const toggleRecoveryMode = (clearErrors: () => void): void => {
        setShowRecoveryInput(!showRecoveryInput);
        clearErrors();
        setCode('');
    };

    return (
        <>
            <Head title="Authentification à deux facteurs" />

            <div className="space-y-6">
                <Form
                    {...store.form()}
                    className="space-y-4"
                    resetOnError
                    resetOnSuccess={!showRecoveryInput}
                >
                    {({ errors, processing, clearErrors }) => (
                        <motion.div 
                            initial="hidden"
                            animate="visible"
                            variants={{
                                visible: {
                                    transition: {
                                        staggerChildren: 0.08,
                                        delayChildren: 0.35
                                    }
                                }
                            }}
                            className="space-y-4"
                        >
                            {showRecoveryInput ? (
                                <motion.div variants={itemVariants}>
                                    <Input
                                        name="recovery_code"
                                        type="text"
                                        placeholder="Saisir le code de récupération"
                                        autoFocus={showRecoveryInput}
                                        required
                                        className="bg-muted border-none shadow-none rounded-xl py-6 px-5 focus-visible:ring-2 focus-visible:ring-primary/50 text-base transition-all duration-300 hover:bg-muted/80 focus-visible:scale-[1.01] focus-visible:-translate-y-0.5 focus-visible:shadow-md"
                                    />
                                    <InputError
                                        message={errors.recovery_code}
                                        className="mt-2"
                                    />
                                </motion.div>
                            ) : (
                                <motion.div variants={itemVariants} className="flex flex-col items-center justify-center space-y-3 text-center">
                                    <div className="flex w-full items-center justify-center">
                                        <InputOTP
                                            name="code"
                                            maxLength={OTP_MAX_LENGTH}
                                            value={code}
                                            onChange={(value) => setCode(value)}
                                            disabled={processing}
                                            pattern={REGEXP_ONLY_DIGITS}
                                            autoFocus
                                            className="transition-all duration-300 hover:scale-[1.01]"
                                        >
                                            <InputOTPGroup>
                                                {Array.from(
                                                    { length: OTP_MAX_LENGTH },
                                                    (_, index) => (
                                                        <InputOTPSlot
                                                            key={index}
                                                            index={index}
                                                            className="h-12 w-12 text-lg border-none bg-muted rounded-md focus:ring-2 focus:ring-primary/50"
                                                        />
                                                    ),
                                                )}
                                            </InputOTPGroup>
                                        </InputOTP>
                                    </div>
                                    <InputError message={errors.code} />
                                </motion.div>
                            )}

                            <motion.div variants={itemVariants}>
                                <Button
                                    type="submit"
                                    className="mt-2 w-full rounded-full py-6 text-base bg-primary hover:bg-primary/90 text-primary-foreground font-medium transition-all duration-300 hover:scale-[1.02] hover:-translate-y-0.5 hover:shadow-lg active:scale-[0.98]"
                                    disabled={processing}
                                >
                                    Continuer
                                </Button>
                            </motion.div>

                            <motion.div variants={itemVariants} className="text-center text-sm text-muted-foreground mt-4">
                                <span>ou vous pouvez </span>
                                <button
                                    type="button"
                                    className="cursor-pointer text-foreground underline decoration-neutral-300 underline-offset-4 transition-colors duration-300 ease-out hover:decoration-current! dark:decoration-neutral-500"
                                    onClick={() =>
                                        toggleRecoveryMode(clearErrors)
                                    }
                                >
                                    {authConfigContent.toggleText}
                                </button>
                            </motion.div>
                        </motion.div>
                    )}
                </Form>
            </div>
        </>
    );
}
