import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Link } from '@inertiajs/react';
import { ArrowRight } from 'lucide-react';
import Logo from '../../assets/chowman-bg-logo.avif';
import Alpona from '../../assets/chowman_alpona.avif';
import Dancing from '../../assets/dancing.avif';
import { Spinner } from '@/components/ui/spinner';
import { useQuizFlow } from '@/features/quiz/hooks';

const STATS = [
    { value: '10', label: 'Questions' },
    { value: '45s', label: 'Each' },
    { value: '1', label: 'Reward' },
];

// Alpona is a square; it scales with screen width but also with screen height
// so the whole page still fits on short phones.
const ALPONA_SIZE = 'min(90vw,360px,42dvh)';
// How much of the alpona's own width sits past the right edge of the screen.
const ALPONA_OFFSET_PERCENT = 27;

/** Mascot that gently floats up and down like a wave. */
const BobbingMascot = () => {
    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(
            [{ transform: 'translateY(-6%)' }, { transform: 'translateY(6%)' }],
            {
                duration: 1800,
                iterations: Infinity,
                direction: 'alternate',
                easing: 'ease-in-out',
            },
        );

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

    return (
        <img
            ref={ref}
            src={Dancing}
            alt=""
            className="pointer-events-none h-auto w-[50%] select-none"
        />
    );
};

export default function Welcome() {
    const { fetchCampaignStatus } = useQuizFlow();
    const [campaignActive, setCampaignActive] = useState<boolean | null>(null);
    const [campaignMessage, setCampaignMessage] = useState<string | null>(null);
    const [loading, setLoading] = useState(true);

    const initializedRef = useRef(false);

    useEffect(() => {
        if (initializedRef.current) {
            return;
        }

        initializedRef.current = true;

        const init = async () => {
            try {
                // Check campaign status
                const campaign = await fetchCampaignStatus();
                setCampaignActive(campaign.data.is_active);

                if (!campaign.data.is_active) {
                    if (campaign.data.status === 'not_started') {
                        setCampaignMessage('Campaign has not started yet.');
                    } else if (campaign.data.status === 'ended') {
                        setCampaignMessage('Campaign has ended.');
                    }
                }
            } catch (error) {
                console.error('Failed to check campaign status:', error);
                setCampaignMessage(
                    'Unable to check campaign status. Please try again.',
                );
            } finally {
                setLoading(false);
            }
        };

        init();
    }, [fetchCampaignStatus]);

    if (loading) {
        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>
        );
    }

    if (!campaignActive) {
        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">
                    <div className="flex justify-center">
                        <img
                            src={Logo}
                            className="h-10 w-auto sm:h-12 sm:w-auto"
                            alt="Chowman Logo"
                        />
                    </div>
                    <div className="mt-10 text-center">
                        <h1 className="font-amethyst text-3xl text-white sm:text-4xl">
                            {campaignMessage || 'Campaign is not active.'}
                        </h1>
                    </div>
                </div>
            </main>
        );
    }

    return (
        <main className="flex min-h-[100dvh] flex-col overflow-x-hidden px-4 py-[clamp(12px,2.5dvh,32px)] sm:px-8 lg:px-12">
            <div className="mx-auto flex w-full max-w-full flex-1 flex-col items-center">
                {/* Logo */}
                <div className="flex shrink-0 justify-center">
                    <img
                        src={Logo}
                        className="h-[clamp(28px,5dvh,48px)] w-auto"
                        alt="Chowman Logo"
                    />
                </div>

                {/* Hero: heading (left) and alpona + mascot (right) share the same vertical centre.
                    The negative right margin lets it reach the screen edge, and overflow-hidden
                    clips the alpona there. */}
                <div
                    className="relative mt-[clamp(8px,2dvh,24px)] -mr-4 flex flex-1 items-center self-stretch overflow-hidden sm:-mr-8 lg:-mr-12"
                    style={{ minHeight: ALPONA_SIZE }}
                >
                    {/* Alpona (spins) with the mascot centred inside it */}
                    <div
                        className="pointer-events-none absolute top-1/2 right-0 aspect-square"
                        style={{
                            width: ALPONA_SIZE,
                            transform: `translate(${ALPONA_OFFSET_PERCENT}%, -50%)`,
                        }}
                    >
                        <img
                            src={Alpona}
                            alt=""
                            className="h-full w-full animate-[spin_40s_linear_infinite] object-contain select-none motion-reduce:animate-none"
                        />
                        <div className="absolute inset-0 flex items-center justify-center">
                            <BobbingMascot />
                        </div>
                    </div>

                    {/* Heading */}
                    <div className="relative z-10 flex shrink-0 flex-col items-start">
                        <p className="font-montserrat text-[10px] font-medium tracking-[0.3em] text-[#E8D9C5] uppercase sm:text-xs">
                            Durga Puja 2026
                        </p>
                        <h1 className="mt-3 font-amethyst text-[clamp(2.25rem,min(13vw,7dvh),4.5rem)] leading-[1.05] text-[#FFF8EA]">
                            <span className='tracking-wider'>The Pujo</span>
                            <br />
                            <span className="text-[#EDC36D] tracking-wider">Quiz</span>
                        </h1>
                        <span className="mt-[clamp(12px,3dvh,32px)] block h-[2px] w-20 bg-[#D4A24E] sm:w-24" />
                    </div>
                </div>

                {/* Description */}
                <p className="mt-[clamp(10px,2.5dvh,28px)] max-w-xs shrink-0 text-center font-montserrat text-xs text-[#E3C7B0] sm:text-sm">
                    Ten questions on the traditions of Sharodiya. Answer well,
                    and a festive treat is yours.
                </p>

                {/* Stats */}
                <div className="mt-[clamp(10px,2.5dvh,32px)] grid w-full shrink-0 grid-cols-3 divide-x divide-[#512F24] border-y border-[#512F24]">
                    {STATS.map((stat) => (
                        <div
                            key={stat.label}
                            className="flex flex-col items-center py-[clamp(8px,1.6dvh,16px)]"
                        >
                            <div className="font-amethyst text-[clamp(1.5rem,3.6dvh,2.25rem)] leading-none text-white">
                                {stat.value}
                            </div>
                            <div className="mt-1 font-montserrat text-[10px] tracking-wider text-[#CBAF8E] uppercase sm:text-xs">
                                {stat.label}
                            </div>
                        </div>
                    ))}
                </div>

                {/* CTA Button */}
                <div className="mt-[clamp(14px,3.5dvh,36px)] w-full max-w-md shrink-0">
                    <Link
                        className="flex h-[clamp(44px,7dvh,84px)] 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:text-[22px] lg:text-[27px]"
                        href="/register"
                    >
                        Begin the Quiz
                        <ArrowRight className="h-5 w-5" />
                    </Link>
                </div>

                {/* Footer note */}
                <p className="mt-[clamp(8px,1.6dvh,16px)] shrink-0 text-center font-montserrat text-[11px] text-[#C5A98B] sm:text-xs">
                    Chowman Durga Puja Quiz & Win · Terms apply
                </p>
            </div>
        </main>
    );
}