import { Head } from '@inertiajs/react';
import { useEffect, useState } from 'react';
import Features from '@/components/home/features';
import Hero from '@/components/home/hero';
import HighDemand from '@/components/home/high-demand';
import NearbyRoutes from '@/components/home/nearby-routes';
import PopularRoutes from '@/components/home/popular-routes';
import SiteFooter from '@/components/home/site-footer';
import SiteHeader from '@/components/home/site-header';
import Stats from '@/components/home/stats';
import type { RoutePrefill, SiteStat, TransferRoute } from '@/types/booking';

type Props = {
    popularRoutes: TransferRoute[];
    highDemandRoutes: TransferRoute[];
    stats: SiteStat[];
    autoDetectLocation: boolean;
};

export default function Welcome({
    popularRoutes,
    highDemandRoutes,
    stats,
    autoDetectLocation,
}: Props) {
    const [prefill, setPrefill] = useState<RoutePrefill | null>(null);
    const [prefillKey, setPrefillKey] = useState(0);

    const applyPrefill = (value: RoutePrefill) => {
        setPrefill(value);
        setPrefillKey(prefillKey + 1);
        requestAnimationFrame(() =>
            document
                .getElementById('book')
                ?.scrollIntoView({ behavior: 'smooth' }),
        );
    };

    useEffect(() => {
        const routeId = Number(
            new URLSearchParams(window.location.search).get('route'),
        );
        const route = [...popularRoutes, ...highDemandRoutes].find(
            (item) => item.id === routeId,
        );

        if (route) {
            applyPrefill({
                routeId: route.id,
                origin: route.origin,
                destination: route.destination,
            });
        }
    }, []);

    return (
        <>
            <Head title="Premium Airport Transfers" />
            <div className="min-h-screen bg-mist font-google text-navy dark:bg-navy">
                <SiteHeader />
                <main>
                    <Hero
                        prefill={prefill}
                        prefillKey={prefillKey}
                        onPrefill={applyPrefill}
                        autoDetectLocation={autoDetectLocation}
                    />
                    {stats.length > 0 && <Stats stats={stats} />}
                    <PopularRoutes routes={popularRoutes} />
                    <NearbyRoutes onPrefill={applyPrefill} />
                    <HighDemand routes={highDemandRoutes} />
                    <Features />
                </main>
                <SiteFooter />
            </div>
        </>
    );
}
