import { useState, useEffect, useLayoutEffect, useRef } from 'react';
import Logo from '../../assets/chowman-bg-logo.avif';
import Alpona from '../../assets/chowman_alpona.avif';
import Eating from '../../assets/eating.avif';
import { router } from '@inertiajs/react';
import { ArrowRight } from 'lucide-react';
import { useQuizFlow, useQuiz } from '@/features/quiz/hooks';
import { useQuizContext } from '@/features/quiz/context';
import { Spinner } from '@/components/ui/spinner';

// Alpona is a square; its centre sits exactly on the progress line.
// It scales with width and height so it never runs up into the logo.
const ALPONA_SIZE = 'min(72vw,300px,32dvh)';

/**
 * Mascot that rises from behind the form card and settles on the progress line.
 * The wrapper handles centring; only the <img> is animated, so the two
 * transforms never fight each other.
 */
const SlideUpMascot = () => {
    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(
            [
                // 100% = the mascot's own height; the extra 48px covers the
                // progress line + gap, so it starts fully hidden behind the form.
                { transform: 'translateY(calc(100% + 48px))' },
                { transform: 'translateY(0)' },
            ],
            {
                duration: 1200,
                delay: 300,
                easing: 'cubic-bezier(0.22, 1, 0.36, 1)', // fast start, soft landing
                fill: 'backwards', // stay hidden during the delay
            },
        );

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

    return (
        <div className="pointer-events-none absolute bottom-0 left-1/2 h-full -translate-x-1/2">
            <img
                ref={ref}
                src={Eating}
                alt=""
                className="block h-full w-auto select-none"
            />
        </div>
    );
};

const Register = () => {
    const { registerGuest, fetchCampaignStatus } = useQuizFlow();
    const { campaign } = useQuiz();
    const { dispatch } = useQuizContext();
    const [name, setName] = useState('');
    const [mobile, setMobile] = useState('');
    const [consent, setConsent] = useState(false);
    const [fieldErrors, setFieldErrors] = useState<Record<string, string[]>>(
        {},
    );
    const [error, setError] = useState<string | null>(null);
    const [isLoadingCampaign, setIsLoadingCampaign] = useState(true);

    // Load guest data from localStorage on mount (for "Change" flow from verify-otp)
    useEffect(() => {
        const fromChange = localStorage.getItem('quiz_from_change');
        if (!fromChange) return;

        localStorage.removeItem('quiz_from_change');

        const savedGuest = localStorage.getItem('quiz_guest');
        if (savedGuest) {
            try {
                const parsed = JSON.parse(savedGuest);
                if (parsed.name) setName(parsed.name);
                if (parsed.mobile) setMobile(parsed.mobile);
            } catch (e) {
                console.error('Failed to parse guest from localStorage');
            }
        }
    }, []);

    // Check campaign status on mount
    useEffect(() => {
        const checkCampaign = async () => {
            try {
                await fetchCampaignStatus();
            } catch (err) {
                // If campaign check fails, allow registration anyway
            } finally {
                setIsLoadingCampaign(false);
            }
        };

        if (!campaign) {
            checkCampaign();
        } else {
            setIsLoadingCampaign(false);
        }
    }, [campaign, fetchCampaignStatus]);

    // Redirect if campaign is not active
    useEffect(() => {
        if (!isLoadingCampaign && campaign && !campaign.is_active) {
            router.visit('/');
        }
    }, [isLoadingCampaign, campaign]);

    if (isLoadingCampaign) {
        return (
            <main className="min-h-[100dvh] px-4 py-8 sm:px-8 lg:px-12">
                <div className="mx-auto flex min-h-[calc(100dvh-64px)] w-full max-w-full flex-col items-center justify-center">
                    <Spinner size="lg" className="text-[#D4A24E]" />
                </div>
            </main>
        );
    }

    const validateName = (value: string) => {
        const trimmed = value.trim();

        if (!trimmed) {
            return 'Full name is required';
        }

        if (trimmed.length < 2 || trimmed.length > 50) {
            return 'Full name must be 2-50 characters';
        }

        if (!/^[a-zA-Z]+(?:\s+[a-zA-Z]+)*$/.test(trimmed)) {
            return 'Full name can only contain letters and spaces';
        }

        return null;
    };

    const validateMobile = (value: string) => {
        if (!value) return 'Mobile number is required';
        const cleaned = value.replace(/\s/g, '');
        if (!/^[6-9]\d{9}$/.test(cleaned))
            return 'Enter a valid 10-digit Indian number starting with 6-9';
        return null;
    };

    const isFormValid = () => {
        return (
            !validateName(name) &&
            !validateMobile(mobile) &&
            consent
        );
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError(null);
        setFieldErrors({});

        const nameError = validateName(name);
        const mobileError = validateMobile(mobile);

        if (nameError) {
            setFieldErrors({ name: [nameError] });
            return;
        }

        if (mobileError) {
            setFieldErrors({ mobile: [mobileError] });
            return;
        }

        if (!consent) {
            setError('Please consent to receive SMS/WhatsApp communications.');
            return;
        }

        try {
            const cleanedMobile = mobile.replace(/\s/g, '');
            await registerGuest({
                name: name.trim(),
                mobile: cleanedMobile,
                consent,
            });
            const guestData = {
                id: 0,
                name: name.trim(),
                mobile: cleanedMobile,
            };
            localStorage.setItem('quiz_guest', JSON.stringify(guestData));
            dispatch({ type: 'SET_GUEST', payload: guestData });
            router.visit('/verify-otp');
        } catch (err: any) {
            // Error is handled by useQuizFlow
        }
    };

    const handleMobileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        let value = e.target.value.replace(/\D/g, '').slice(0, 10);
        // Format as XXXXX XXXXX
        if (value.length > 5) {
            value = value.slice(0, 5) + ' ' + value.slice(5);
        }
        setMobile(value);
    };

    return (
        <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-[55px] sm:px-8 lg:rounded-[65px] lg:px-12">
                <div className="relative mx-auto flex w-full max-w-[700px] flex-1 flex-col sm:max-w-[760px] lg:max-w-full">
                    {/* 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">
                            <SlideUpMascot />
                            <span className="relative font-montserrat text-sm font-bold text-[#D4A24E] sm:text-[21px] lg:text-[24px]">
                                01 / 02
                            </span>
                        </div>

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

                    {/* Form (sits above the bottom of the alpona) */}
                    <form
                        onSubmit={handleSubmit}
                        className="relative z-10 mt-[clamp(12px,2.5dvh,20px)] rounded-[38px] bg-[#F8DDB2] px-6 py-[clamp(20px,4.5dvh,36px)] sm:mt-[clamp(20px,4dvh,40px)] sm:rounded-[48px] sm:px-10 sm:py-11 lg:rounded-[55px] lg:px-14 lg:py-14"
                    >
                        {/* Full Name */}
                        <div>
                            <label className="font-montserrat text-xs font-bold text-[#5A4233] sm:text-[17px] lg:text-[19px]">
                                FULL NAME
                            </label>

                            <input
                                type="text"
                                placeholder="e.g. Ananya Sen"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                className={`mt-1 h-10 w-full rounded-lg border bg-white px-5 font-montserrat text-sm text-[#5A4233] outline-none placeholder:text-[#B4A894] focus:border-[#D4A24E] sm:h-[62px] sm:px-6 sm:text-[20px] lg:h-[68px] lg:px-7 lg:text-[22px] ${
                                    fieldErrors.name
                                        ? 'border-red-500'
                                        : 'border-[#D6C9B4]'
                                }`}
                            />

                            {fieldErrors.name && (
                                <p className="mt-2 px-1 font-montserrat text-xs text-red-500 sm:text-[15px] lg:text-[16px]">
                                    {fieldErrors.name[0]}
                                </p>
                            )}
                            {!fieldErrors.name && (
                                <p className="mt-2 px-1 font-montserrat text-xs text-[#917F69] sm:text-[15px] lg:text-[16px]">
                                    2–50 characters, letters and spaces only
                                </p>
                            )}
                        </div>

                        {/* Mobile */}
                        <div className="mt-[clamp(10px,2dvh,16px)] sm:mt-8 lg:mt-10">
                            <label className="font-montserrat text-xs font-bold text-[#5A4233] sm:text-[17px] lg:text-[19px]">
                                MOBILE NUMBER
                            </label>

                            <div
                                className={`mt-1 flex h-10 w-full overflow-hidden rounded-xl border bg-white sm:h-[62px] lg:h-[68px] ${
                                    fieldErrors.mobile
                                        ? 'border-red-500'
                                        : 'border-[#D6C9B4]'
                                }`}
                            >
                                <div className="flex w-[60px] shrink-0 items-center border-r border-[#D6C9B4] px-5 font-montserrat text-sm font-bold text-[#5A4233] sm:w-[115px] sm:px-6 sm:text-[18px] lg:w-[130px] lg:px-7 lg:text-[20px]">
                                    +91
                                </div>

                                <input
                                    type="tel"
                                    placeholder="98765 43210"
                                    value={mobile}
                                    onChange={handleMobileChange}
                                    className="min-w-0 flex-1 bg-transparent px-5 font-montserrat text-sm text-[#5A4233] outline-none placeholder:text-[#B4A894] sm:px-6 sm:text-[20px] lg:px-7 lg:text-[22px]"
                                />
                            </div>

                            {fieldErrors.mobile && (
                                <p className="mt-2 px-1 font-montserrat text-xs text-red-500 sm:text-[15px] lg:text-[16px]">
                                    {fieldErrors.mobile[0]}
                                </p>
                            )}
                            {!fieldErrors.mobile && (
                                <p className="mt-2 px-1 font-montserrat text-xs text-[#917F69] sm:text-[15px] lg:text-[16px]">
                                    10 digit Indian numbers starting 6–9
                                </p>
                            )}
                        </div>

                        {/* Divider */}
                        <div className="my-[clamp(12px,2.5dvh,24px)] h-px bg-[#D6C9B4] sm:my-7 lg:my-8" />

                        {/* Consent */}
                        <label className="flex cursor-pointer items-start gap-4 px-1 sm:gap-5 lg:gap-6">
                            <span className="relative mt-1 shrink-0">
                                <input
                                    type="checkbox"
                                    checked={consent}
                                    onChange={(e) =>
                                        setConsent(e.target.checked)
                                    }
                                    className="peer h-4 w-4 appearance-none border border-[#B9A98F] bg-white checked:border-[#D4A24E] checked:bg-[#D4A24E] sm:h-[38px] sm:w-[38px] lg:h-[44px] lg:w-[44px]"
                                />

                                <span className="pointer-events-none absolute top-2/5 left-1/2 h-2 w-1 -translate-x-1/2 -translate-y-1/2 rotate-45 border-r-2 border-b-2 border-white opacity-0 peer-checked:opacity-100 sm:h-[17px] sm:w-[10px] lg:h-5 lg:w-3" />
                            </span>

                            <span className="font-montserrat text-xs leading-[1.3] text-[#5A4233] sm:text-[18px] lg:text-[21px]">
                                I agree to receive offers, updates, and other communications from
                                Chowman via SMS/WhatsApp.&nbsp;
                                <a
                                    className="font-bold underline underline-offset-2"
                                    href="/privacy-policy"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                >
                                    Privacy Policy
                                </a>
                            </span>
                        </label>

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

                    {/* Send OTP */}
                    <div className="my-auto pt-[clamp(12px,3dvh,32px)] pb-[clamp(12px,3dvh,32px)] sm:pt-10 sm:pb-10 lg:pt-12 lg:pb-14">
                        <button
                            type="button"
                            onClick={handleSubmit}
                            disabled={!isFormValid()}
                            className={`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:h-[72px] sm:text-[22px] lg:h-[84px] lg:text-[27px] ${
                                !isFormValid()
                                    ? 'cursor-not-allowed opacity-30'
                                    : 'opacity-100'
                            }`}
                        >
                            Get OTP
                            <ArrowRight className="h-5 w-5" />
                        </button>

                        <p className="mt-5 text-center font-montserrat text-xs text-[#C5A98B] sm:mt-6 sm:text-[15px] lg:mt-8 lg:text-[17px]">
                            Used only to verify your entry — never shared
                        </p>
                    </div>
                </div>
            </div>
        </main>
    );
};

export default Register;