import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import Logo from '../../assets/chowman-bg-logo.avif';
import Alpona from '../../assets/chowman_alpona.avif';
import Serving from '../../assets/serving.avif';
import { Link, router } from '@inertiajs/react';
import { ArrowRight } from 'lucide-react';
import { useQuizFlow, useQuiz } from '@/features/quiz/hooks';
import { QuizRouteGuard } from '@/features/quiz/components';

// Alpona is a square; its centre sits exactly on the progress line.
// Same value as the Register page so both screens match.
const ALPONA_SIZE = 'min(72vw,300px,32dvh)'; 

/** Image that is revealed with a bottom-to-top wipe. */
const WipeMascot = ({ className = '' }: { className?: string }) => {
    const ref = useRef<HTMLImageElement>(null);

    useLayoutEffect(() => {
        const el = ref.current;
        if (!el) return;
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

        const animation = el.animate(
            [
                { clipPath: 'inset(100% 0 0 0)' }, // fully hidden
                { clipPath: 'inset(0 0 0 0)' },    // fully revealed
            ],
            {
                duration: 1100,
                delay: 300,
                easing: 'cubic-bezier(0.65, 0, 0.35, 1)',
                fill: 'backwards',
            },
        );

        return () => animation.cancel();
    }, []);

    return <img ref={ref} src={Serving} alt="" className={className} />;
};

const VerifyOTP = () => {
    const { verifyOtp, resendOtp } = useQuizFlow();
    const { guest } = useQuiz();
    const [otp, setOtp] = useState(['', '', '', '', '', '']);
    const [resendCountdown, setResendCountdown] = useState(30);
    const [canResend, setCanResend] = useState(false); 
    const [otpExpiry, setOtpExpiry] = useState(300); // 5 minutes
    const [error, setError] = useState<string | null>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const inputRefs = useRef<(HTMLInputElement | null)[]>([]); 

    useEffect(() => {
        const timer = setTimeout(() => {
            inputRefs.current[0]?.focus();
        }, 2000);

        return () => clearTimeout(timer);
    }, []); 

    // OTP expiry countdown - 5 minutes
    useEffect(() => {
        if (otpExpiry <= 0) return;

        const timer = setTimeout(() => {
            setOtpExpiry((prev) => prev - 1);
        }, 1000);

        return () => clearTimeout(timer);
    }, [otpExpiry]);

    // Load guest from localStorage on mount
    useEffect(() => {
        const savedGuest = localStorage.getItem('quiz_guest');
        if (savedGuest) {
            try {
                const parsed = JSON.parse(savedGuest);
                // Guest is loaded via context, no need to set here
            } catch (e) {
                console.error('Failed to parse guest from localStorage');
            }
        }
    }, []);

    // Resend countdown
    useEffect(() => {
        if (resendCountdown > 0 && !canResend) {
            const timer = setTimeout(() => {
                setResendCountdown(resendCountdown - 1);
            }, 1000);
            return () => clearTimeout(timer);
        } else if (resendCountdown === 0 && !canResend) {
            setCanResend(true);
        }
    }, [resendCountdown, canResend]);

    const handleChange = (index: number, value: string) => {
        const digit = value.replace(/\D/g, '').slice(-1);

        const newOtp = [...otp];
        newOtp[index] = digit;
        setOtp(newOtp);
        setError(null);

        if (digit && index < 5) {
            inputRefs.current[index + 1]?.focus();
        }
    };

    const handleKeyDown = (
        index: number,
        e: React.KeyboardEvent<HTMLInputElement>,
    ) => {
        if (e.key === 'Backspace' && !otp[index] && index > 0) {
            inputRefs.current[index - 1]?.focus();
        }
    };

    const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
        const digits = e.clipboardData
            .getData('text')
            .replace(/\D/g, '')
            .slice(0, 6);
        if (!digits) return;
        e.preventDefault();
        setOtp(Array.from({ length: 6 }, (_, index) => digits[index] ?? ''));
        inputRefs.current[Math.min(digits.length, 6) - 1]?.focus();
        setError(null);
    };

    const handleResend = async () => {
        if (!canResend || !guest) return;

        try {
            const response = await resendOtp(guest.mobile);

            setResendCountdown(response.data.resend_available_in);
            setCanResend(response.data.resend_available_in === 0);
            setOtpExpiry(300);
            setError(null);

            // Optional: clear old OTP
            setOtp(['', '', '', '', '', '']);
            inputRefs.current[0]?.focus();
        } catch (err: any) {
            // Error is handled by useQuizFlow
        }
    };

    const handleSubmit = async () => {
        const otpValue = otp.join('');
        if (otpValue.length !== 6) {
            setError('Please enter all 6 digits');
            return;
        }

        if (!guest) {
            setError('Session expired. Please register again.');
            return;
        }

        setIsSubmitting(true);
        setError(null);

        try {
            await verifyOtp(guest.mobile, otpValue);
            // Navigation is handled by useQuizFlow based on state
        } catch (err: any) {
            // Error is handled by useQuizFlow
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleEdit = () => {
        localStorage.setItem('quiz_from_change', 'true');
        router.visit('/register');
    };

    const maskedMobile = guest?.mobile
        ? `${guest.mobile.slice(0, 5)} ${guest.mobile.slice(5)}`
        : '+91 XXXXX XXXXX';

    const formatCountdown = (seconds: number) => {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins}:${secs.toString().padStart(2, '0')}`;
    };

    return (
        <QuizRouteGuard>
            <main className="flex min-h-[100dvh] flex-col overflow-x-hidden px-4 py-[clamp(12px,3dvh,32px)] sm:px-8 sm:py-8 lg:px-12">
                <div className="relative mx-auto flex w-full flex-1 flex-col rounded-[45px] px-5 sm:rounded-[70px] sm:px-8">
                    <div className="relative mx-auto flex w-full max-w-[700px] flex-1 flex-col">
                        {/* Logo */}
                        <div className="flex justify-center">
                            <img
                                src={Logo}
                                className="h-10 w-auto sm:h-12 sm:w-auto"
                                alt="Chowman Logo"
                            />
                        </div>

                        {/* Mascot + progress. The alpona is centred on the progress line. */}
                        <div className="relative mt-[clamp(8px,2.5dvh,40px)]">
                            {/* Spinning alpona: centre = bottom edge of this block = the progress line */}
                            {/* <div
                                className="pointer-events-none absolute bottom-0 left-1/2"
                                style={{
                                    width: ALPONA_SIZE,
                                    height: ALPONA_SIZE,
                                    transform: 'translate(-50%, 50%)',
                                }}
                            >
                                <img
                                    src={Alpona}
                                    alt=""
                                    className="h-full w-full animate-[spin_40s_linear_infinite] object-contain select-none motion-reduce:animate-none"
                                />
                            </div> */}

                            {/* Mascot (centred, resting on the line) + step counter */}
                            <div className="relative z-10 flex h-[clamp(100px,16dvh,160px)] items-end justify-end">
                                <WipeMascot className="pointer-events-none absolute bottom-0 left-1/2 h-full w-auto -translate-x-1/2 select-none" />
                                <span className="relative font-montserrat text-sm font-bold text-[#D4A24E] sm:text-[27px]">
                                    02 / 02
                                </span>
                            </div>

                            {/* Progress line */}
                            <div className="relative z-10 mt-1 h-px w-full bg-[#D4A24E]">
                                {/* <div className="absolute left-0 top-0 h-px w-2/3 bg-[#D4A24E]" /> */}
                            </div>
                        </div>

                        {/* Verification Content (above the alpona) */}
                        <div className="relative z-10 mt-[clamp(16px,4dvh,40px)] sm:mt-28">
                            <p className="text-center font-montserrat text-xs font-bold text-[#D4A24E] sm:text-[20px]">
                                VERIFICATION
                            </p>

                            <h1 className="mt-[clamp(10px,2dvh,20px)] text-center font-amethyst text-2xl leading-[1.15] text-[#FFF8EA] sm:mt-6 sm:text-[48px] lg:text-[52px]">
                                <span className="tracking-wider">Enter your OTP</span>
                            </h1>

                            <p className="mt-[clamp(10px,2dvh,20px)] text-center font-montserrat text-xs text-[#C5A98B] sm:mt-6 sm:text-[20px]">
                                Sent to +91 {maskedMobile}
                                <span className="mx-2">·</span>
                                <button
                                    onClick={handleEdit}
                                    className="underline underline-offset-2"
                                >
                                    Change
                                </button>
                            </p>

                            {/* OTP Box */}
                            <div className="mt-[clamp(16px,3.5dvh,48px)] rounded-[38px] bg-[#F8DDB2] px-4 py-[clamp(12px,2.5dvh,24px)] min-[380px]:px-6 sm:mt-9 sm:rounded-[48px] sm:px-11 sm:py-14 lg:rounded-[55px] lg:px-12 lg:py-16"> 
                                <p className="mb-5 text-center font-montserrat text-sm font-semibold text-[#5A4233] sm:mb-7 sm:text-[20px]">
                                    OTP expires in{' '}
                                    <span className="text-[#D4A24E]">
                                        {formatCountdown(otpExpiry)}
                                    </span>
                                </p>
                                <div className="flex justify-center gap-2 min-[380px]:gap-3 sm:gap-5 lg:gap-6">
                                    {otp.map((digit, index) => (
                                        <input
                                            key={index}
                                            ref={(el) => {
                                                inputRefs.current[index] = el;
                                            }}
                                            type="text"
                                            inputMode="numeric"
                                            autoComplete={
                                                index === 0
                                                    ? 'one-time-code'
                                                    : 'off'
                                            }
                                            maxLength={1}
                                            value={digit}
                                            onChange={(e) =>
                                                handleChange(
                                                    index,
                                                    e.target.value,
                                                )
                                            }
                                            onKeyDown={(e) =>
                                                handleKeyDown(index, e)
                                            }
                                            onPaste={handlePaste}
                                            disabled={isSubmitting}
                                            className="aspect-square max-w-[45px] min-w-0 flex-1 rounded-md border border-[#D6C9B4] bg-white p-0 text-center font-serif text-[26px] text-[#230505] outline-none focus:border-[#D4A24E] disabled:opacity-50 min-[380px]:text-[32px] sm:max-w-[72px] sm:text-[38px] lg:max-w-[78px] lg:text-[40px]"
                                        />
                                    ))}
                                </div>

                                {error && (
                                    <p className="mt-4 text-center font-montserrat text-xs text-red-500 sm:text-sm">
                                        {error}
                                    </p>
                                )}

                                {/* Verify Button */}
                                <button
                                    type="button"
                                    onClick={handleSubmit}
                                    disabled={
                                        otp.join('').length !== 6 ||
                                        isSubmitting
                                    }
                                    className={`mt-[clamp(16px,3dvh,32px)] flex h-14 w-full items-center justify-center gap-2 rounded-xl border border-[#F0D28E] bg-gradient-to-b from-[#E7C27A] to-[#CEA052] font-montserrat text-sm font-bold text-[#230505] sm:mt-10 sm:h-[72px] sm:text-[22px] lg:h-[84px] lg:text-[27px] ${
                                        otp.join('').length !== 6 ||
                                        isSubmitting
                                            ? 'cursor-not-allowed opacity-30'
                                            : 'opacity-100'
                                    }`}
                                >
                                    {isSubmitting
                                        ? 'Verifying...'
                                        : 'Verify & Begin'}
                                    {!isSubmitting && (
                                        <ArrowRight className="h-5 w-5" />
                                    )}
                                </button>

                                <p className="mt-[clamp(12px,2.5dvh,24px)] text-center font-montserrat text-sm text-[#917F69] sm:mt-8 sm:text-[20px]">
                                    Didn't receive it?{' '}
                                    {canResend ? (
                                        <button
                                            type="button"
                                            onClick={handleResend}
                                            className="text-[#D4A24E] underline underline-offset-2"
                                        >
                                            Resend
                                        </button>
                                    ) : (
                                        <span>
                                            Resend in{' '}
                                            {formatCountdown(resendCountdown)}
                                        </span>
                                    )}
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </QuizRouteGuard>
    );
};

export default VerifyOTP;