import PublicPageHeading from '@/components/public-page-heading';
import CinematicPageScene from '@/components/cinematic-page-scene';
import { Head, Link } from '@inertiajs/react';
import { motion, useReducedMotion, type MotionProps } from 'framer-motion';
import {
    CalendarDays,
    FlagTriangleRight,
    MapPin,
    Search,
    Ticket,
} from 'lucide-react';
import { SiteActionLink, SiteButton } from '@/components/site-action';
import RaceImage from '@/components/race-image';
import SiteLayout from '@/components/site-layout';

type EventItem = {
    id: number;
    title: string;
    slug: string;
    discipline: string | null;
    starts_at: string | null;
    venue: string | null;
    location: string | null;
    organizer: string;
    organizer_slug: string;
    tickets_from: number;
    banner_url: string | null;
    description: string | null;
};

type EventPage = {
    data: EventItem[];
    total: number;
    current_page: number;
    last_page: number;
    links: { url: string | null; label: string; active: boolean }[];
};

const eventImages = [
    'https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=crop&w=1600&q=85',
    'https://images.unsplash.com/photo-1504215680853-026ed2a45def?auto=format&fit=crop&w=1200&q=85',
    'https://images.unsplash.com/photo-1503736334956-4c8f8e92946d?auto=format&fit=crop&w=1200&q=85',
    'https://images.unsplash.com/photo-1511919884226-fd3cad34687c?auto=format&fit=crop&w=1200&q=85',
];

function formattedDate(
    date: string | null,
    style: 'long' | 'short' = 'long',
): string {
    if (!date) {
        return 'Date to be announced';
    }

    return new Date(date).toLocaleDateString(
        'en-LK',
        style === 'long'
            ? {
                  weekday: 'short',
                  day: 'numeric',
                  month: 'long',
                  year: 'numeric',
              }
            : { day: '2-digit', month: 'short' },
    );
}

function monthLabel(date: string | null): string {
    return date
        ? new Date(date).toLocaleDateString('en-LK', {
              month: 'long',
              year: 'numeric',
          })
        : 'Date to be announced';
}

function scheduleGroups(events: EventItem[]): [string, EventItem[]][] {
    const groups = new Map<string, EventItem[]>();

    events.forEach((event) => {
        const label = monthLabel(event.starts_at);
        groups.set(label, [...(groups.get(label) ?? []), event]);
    });

    return Array.from(groups.entries());
}

function filterHref(query: string, discipline: string): string {
    const params = new URLSearchParams();
    if (query) {
        params.set('q', query);
    }
    if (discipline) {
        params.set('discipline', discipline);
    }

    const search = params.toString();
    return search ? `/events?${search}` : '/events';
}

function pageLabel(label: string): string {
    return label.replace(/&laquo;|&raquo;/g, '').trim();
}

export default function EventsIndex({
    events,
    filters,
    disciplines,
}: {
    events: EventPage;
    filters: { q: string; discipline: string };
    disciplines: string[];
}) {
    const reduceMotion = useReducedMotion();
    const featuredEvent = events.data[0];
    const remainingEvents = events.data.slice(1);
    const groups = scheduleGroups(remainingEvents);
    const reveal: MotionProps = reduceMotion
        ? {}
        : {
              initial: { opacity: 0, y: 18 },
              whileInView: { opacity: 1, y: 0 },
              viewport: { once: true, amount: 0.12 },
              transition: { duration: 0.45, ease: 'easeOut' },
          };
    const hasFilters = Boolean(filters.q || filters.discipline);

    return (
        <SiteLayout pageClassName="paddock-page">
            <Head title="Motorsport Events in Sri Lanka">
                <meta
                    name="description"
                    content="Find upcoming motorcycle, car and motorsport events across Sri Lanka. See the schedule, entries and tickets."
                />
            </Head>

            <PublicPageHeading
                eyebrow="The race calendar"
                title={
                    <>
                        YOUR NEXT{' '}
                        <span className="text-[#e6342b]">RACE DAY.</span>
                    </>
                }
                description="Find the circuits, rally stages and race weekends bringing Sri Lankan motorsport together."
                metrics={[{ label: 'Published events', value: events.total }]}
            >
                <form
                    method="get"
                    action="/events"
                    role="search"
                    className="public-heading-search flex max-w-2xl flex-wrap items-center gap-2 rounded-xl border border-[#111516]/12 bg-[#f7f5ef] p-2 shadow-sm focus-within:border-[#e8422b]/60 focus-within:ring-2 focus-within:ring-[#e8422b]/10"
                >
                    {filters.discipline && (
                        <input
                            type="hidden"
                            name="discipline"
                            value={filters.discipline}
                        />
                    )}
                    <Search
                        size={18}
                        aria-hidden="true"
                        className="ml-2 shrink-0 text-[#c83221]"
                    />
                    <label htmlFor="events-search" className="sr-only">
                        Search events, venues, locations and disciplines
                    </label>
                    <input
                        id="events-search"
                        name="q"
                        type="search"
                        defaultValue={filters.q}
                        placeholder="Search events, venues or locations"
                        className="min-w-44 flex-1 bg-transparent px-2 py-2.5 text-sm font-semibold text-[#17191b] outline-none placeholder:font-medium placeholder:text-[#888c85]"
                    />
                    <SiteButton type="submit" variant="dark" size="sm">
                        Search
                    </SiteButton>
                </form>

                <nav
                    aria-label="Filter events by discipline"
                    className="mt-3 flex [scrollbar-width:none] gap-2 overflow-x-auto pb-1"
                >
                    {['All races', ...disciplines].map((discipline) => {
                        const value =
                            discipline === 'All races' ? '' : discipline;
                        const active = filters.discipline === value;

                        return (
                            <Link
                                key={discipline}
                                href={filterHref(filters.q, value)}
                                preserveScroll
                                aria-current={active ? 'page' : undefined}
                                className={`inline-flex min-h-9 shrink-0 items-center rounded-full border px-3.5 text-xs font-black transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#e8422b] ${active ? 'border-[#111516] bg-[#111516] text-white' : 'border-[#111516]/15 bg-[#f7f5ef] text-[#4d5550] hover:border-[#e8422b]/60 hover:text-[#b92d21]'}`}
                            >
                                {discipline}
                            </Link>
                        );
                    })}
                </nav>
            </PublicPageHeading>

            <CinematicPageScene
                eyebrow="The racing calendar"
                title="The next start is closer than it looks."
                description="From circuit battles to open-road stages, find the weekend that brings you trackside."
                image="https://images.unsplash.com/photo-1503376780353-7e6692767b70?auto=format&fit=crop&w=2200&q=85"
                imageAlt="Motorsport car on a race circuit at speed"
            />

            <main className="bg-[#e9e6dc] pb-14">
                <section className="mx-auto max-w-7xl px-5 py-8 lg:px-8 lg:py-10">
                    <div className="flex flex-wrap items-end justify-between gap-4">
                        <div>
                            <p className="text-[10px] font-black tracking-[.22em] text-[#e8422b] uppercase">
                                Race finder
                            </p>
                            <h2 className="mt-1 text-xl font-black tracking-[-.045em] text-[#111516] sm:text-2xl">
                                Find a race
                            </h2>
                        </div>
                        <p className="text-xs font-semibold text-[#5d655f]">
                            Showing {events.data.length} of {events.total}{' '}
                            events
                        </p>
                    </div>

                    {featuredEvent ? (
                        <>
                            <motion.article {...reveal} className="mt-7">
                                <div className="group relative flex min-h-[330px] overflow-hidden rounded-2xl bg-[#111516] p-5 text-white shadow-lg shadow-[#111516]/10 sm:min-h-[360px] sm:p-8">
                                    <RaceImage
                                        src={featuredEvent.banner_url}
                                        fallbackSrc={eventImages[0]}
                                        alt={`Race imagery for ${featuredEvent.title}`}
                                        className="absolute inset-0 size-full object-cover opacity-55 transition duration-700 group-hover:scale-[1.03] group-hover:opacity-70"
                                    />
                                    {!featuredEvent.banner_url && (
                                        <span className="absolute top-4 right-4 rounded-full bg-[#111516]/70 px-3 py-1.5 text-[10px] font-bold text-white backdrop-blur-sm">
                                            Placeholder photo · Unsplash
                                        </span>
                                    )}
                                    <div className="absolute inset-0 bg-[linear-gradient(90deg,rgba(7,9,9,.92)_0%,rgba(7,9,9,.62)_48%,rgba(7,9,9,.12)_100%)]" />
                                    <div className="relative flex w-full flex-col justify-between gap-10">
                                        <span className="w-fit rounded-full bg-[#f6c84f] px-3 py-1.5 text-[10px] font-black tracking-[.16em] text-[#111516] uppercase">
                                            Next on the calendar
                                        </span>
                                        <div className="max-w-2xl">
                                            <p className="flex items-center gap-2 text-xs font-black tracking-[.14em] text-[#f6c84f] uppercase">
                                                <CalendarDays
                                                    size={15}
                                                    aria-hidden="true"
                                                />
                                                {formattedDate(
                                                    featuredEvent.starts_at,
                                                )}
                                                {featuredEvent.discipline && (
                                                    <>
                                                        <span className="text-white/40">
                                                            ·
                                                        </span>
                                                        {
                                                            featuredEvent.discipline
                                                        }
                                                    </>
                                                )}
                                            </p>
                                            <h2 className="mt-3 text-3xl leading-[.94] font-black tracking-[-.06em] sm:text-5xl">
                                                <Link
                                                    href={`/events/${featuredEvent.slug}`}
                                                    className="hover:text-[#f6c84f] focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-[#f6c84f]"
                                                >
                                                    {featuredEvent.title}
                                                </Link>
                                            </h2>
                                            {featuredEvent.description && (
                                                <p className="mt-3 line-clamp-2 max-w-xl text-sm leading-6 text-white/75">
                                                    {featuredEvent.description
                                                        .replace(/\s+/g, ' ')
                                                        .trim()}
                                                </p>
                                            )}
                                            <div className="mt-4 flex flex-wrap items-center gap-x-5 gap-y-2 text-xs text-white/75">
                                                <span className="flex items-center gap-1.5">
                                                    <MapPin
                                                        size={14}
                                                        className="text-[#e8422b]"
                                                        aria-hidden="true"
                                                    />
                                                    {featuredEvent.venue ||
                                                        'Venue to be announced'}
                                                    {featuredEvent.location
                                                        ? ` · ${featuredEvent.location}`
                                                        : ''}
                                                </span>
                                                <span>
                                                    Hosted by{' '}
                                                    <Link
                                                        href={`/organizers/${featuredEvent.organizer_slug}`}
                                                        className="font-bold text-white hover:text-[#f6c84f]"
                                                    >
                                                        {
                                                            featuredEvent.organizer
                                                        }
                                                    </Link>
                                                </span>
                                            </div>
                                            <SiteActionLink
                                                href={`/events/${featuredEvent.slug}`}
                                                variant="hover-outline-inverse"
                                                className="mt-5 text-sm"
                                            >
                                                View race details
                                            </SiteActionLink>
                                        </div>
                                    </div>
                                </div>
                            </motion.article>

                            {groups.length > 0 && (
                                <div className="mt-8 space-y-7">
                                    {groups.map(([month, monthEvents]) => (
                                        <section key={month} aria-label={month}>
                                            <div className="mb-2 flex items-center justify-between border-b border-[#111516]/12 pb-2">
                                                <h2 className="text-base font-black tracking-tight text-[#111516] sm:text-lg">
                                                    {month}
                                                </h2>
                                                <span className="text-[10px] font-bold tracking-[.12em] text-[#747a77] uppercase">
                                                    {monthEvents.length}{' '}
                                                    {monthEvents.length === 1
                                                        ? 'race'
                                                        : 'races'}
                                                </span>
                                            </div>
                                            <div className="divide-y divide-[#d9d5ca]">
                                                {monthEvents.map(
                                                    (event, index) => (
                                                        <EventScheduleRow
                                                            key={event.id}
                                                            event={event}
                                                            image={
                                                                eventImages[
                                                                    (index +
                                                                        1) %
                                                                        eventImages.length
                                                                ]
                                                            }
                                                            reveal={reveal}
                                                        />
                                                    ),
                                                )}
                                            </div>
                                        </section>
                                    ))}
                                </div>
                            )}

                            {events.links.length > 3 && (
                                <nav
                                    aria-label="Event schedule pages"
                                    className="mt-8 flex flex-wrap items-center justify-center gap-2"
                                >
                                    {events.links.map((link, index) => (
                                        <Link
                                            key={`${link.label}-${index}`}
                                            href={link.url || '#'}
                                            aria-current={
                                                link.active ? 'page' : undefined
                                            }
                                            aria-disabled={!link.url}
                                            preserveScroll
                                            className={`inline-flex min-h-10 min-w-10 items-center justify-center rounded-lg border px-3 text-sm font-bold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#e8422b] ${link.active ? 'border-[#111516] bg-[#111516] text-white' : link.url ? 'border-[#111516]/15 bg-[#f7f5ef] text-[#454b47] hover:border-[#e8422b]/60 hover:text-[#b92d21]' : 'pointer-events-none border-[#111516]/8 text-[#a6a8a1]'}`}
                                        >
                                            {pageLabel(link.label)}
                                        </Link>
                                    ))}
                                </nav>
                            )}
                        </>
                    ) : (
                        <motion.div
                            {...reveal}
                            className="mt-7 rounded-2xl border border-dashed border-[#111516]/20 bg-[#f7f5ef] p-8 text-center sm:p-10"
                        >
                            <FlagTriangleRight
                                className="mx-auto text-[#e8422b]"
                                aria-hidden="true"
                            />
                            <p className="mt-4 text-lg font-black text-[#111516]">
                                {hasFilters
                                    ? 'No races match your search'
                                    : 'The calendar is warming up'}
                            </p>
                            <p className="mx-auto mt-2 max-w-md text-sm leading-6 text-[#606762]">
                                {hasFilters
                                    ? 'Try another event, venue or discipline to find the race you are looking for.'
                                    : 'There are no published events yet. Check back when the next race weekend is announced.'}
                            </p>
                            {hasFilters && (
                                <SiteActionLink
                                    href="/events"
                                    variant="outline"
                                    className="mt-5"
                                >
                                    Clear search
                                </SiteActionLink>
                            )}
                        </motion.div>
                    )}
                </section>
            </main>
        </SiteLayout>
    );
}

function EventScheduleRow({
    event,
    image,
    reveal,
}: {
    event: EventItem;
    image: string;
    reveal: MotionProps;
}) {
    return (
        <motion.article
            {...reveal}
            className="grid grid-cols-[84px_minmax(0,1fr)] items-center gap-3 py-3 sm:grid-cols-[112px_minmax(0,1fr)_auto] sm:gap-4"
        >
            <div className="relative h-[76px] overflow-hidden rounded-xl bg-[#111516] sm:h-[84px]">
                <RaceImage
                    src={event.banner_url}
                    fallbackSrc={image}
                    alt={`Race imagery for ${event.title}`}
                    className="size-full object-cover transition duration-500 hover:scale-105"
                />
                {!event.banner_url && (
                    <span className="absolute right-1 bottom-1 rounded bg-[#111516]/75 px-1.5 py-0.5 text-[8px] font-bold text-white">
                        Unsplash
                    </span>
                )}
            </div>
            <div className="min-w-0">
                <p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[10px] font-black tracking-[.1em] text-[#c83221] uppercase">
                    <span>{formattedDate(event.starts_at, 'short')}</span>
                    {event.discipline && (
                        <span className="text-[#99968d]">
                            · {event.discipline}
                        </span>
                    )}
                </p>
                <h3 className="mt-1 truncate text-base leading-tight font-black tracking-[-.025em] text-[#111516] sm:text-lg">
                    <Link
                        href={`/events/${event.slug}`}
                        className="hover:text-[#c83221]"
                    >
                        {event.title}
                    </Link>
                </h3>
                <p className="mt-1 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[#626a64]">
                    <span className="flex min-w-0 items-center gap-1">
                        <MapPin
                            size={12}
                            className="shrink-0 text-[#e8422b]"
                            aria-hidden="true"
                        />
                        <span className="truncate">
                            {event.venue || event.location || 'Venue TBA'}
                        </span>
                        {event.venue && event.location && (
                            <span className="truncate">· {event.location}</span>
                        )}
                    </span>
                    <Link
                        href={`/organizers/${event.organizer_slug}`}
                        className="truncate font-semibold hover:text-[#c83221]"
                    >
                        {event.organizer}
                    </Link>
                </p>
            </div>
            <div className="col-span-2 flex items-center justify-between gap-3 border-t border-[#111516]/8 pt-2 sm:col-span-1 sm:flex-col sm:items-end sm:border-0 sm:pt-0">
                <span className="flex items-center gap-1.5 text-xs font-black text-[#111516]">
                    <Ticket
                        size={14}
                        className="text-[#e8422b]"
                        aria-hidden="true"
                    />
                    {event.tickets_from > 0
                        ? `From LKR ${Number(event.tickets_from).toLocaleString()}`
                        : 'Tickets TBA'}
                </span>
                <SiteActionLink
                    href={`/events/${event.slug}`}
                    variant="outline"
                    size="sm"
                >
                    View event
                </SiteActionLink>
            </div>
        </motion.article>
    );
}
