import PublicPageHeading from '@/components/public-page-heading';
import CinematicPageScene from '@/components/cinematic-page-scene';
import { Head, Link } from '@inertiajs/react';
import { Search, Trophy } from 'lucide-react';
import { SiteActionLink, SiteButton } from '@/components/site-action';
import SiteLayout from '@/components/site-layout';

type ResultRow = {
    event: string;
    event_slug: string;
    starts_at: string | null;
    profile: { name: string; slug: string; type: string };
    race_class: string | null;
    race_number: string | null;
    position: number | null;
    result_status: string;
    time: string | null;
    points: number | null;
};
type Leaderboard = {
    event: string;
    event_slug: string;
    starts_at: string | null;
    race_class: string;
    results: ResultRow[];
};
type Page<T> = {
    data: T[];
    links: { url: string | null; label: string; active: boolean }[];
    total: number;
};

function statusLabel(status: string): string {
    return status.replaceAll('_', ' ');
}

export default function ResultsIndex({
    results,
    filters,
}: {
    results: Page<Leaderboard>;
    filters: { q: string; event: string; class: string; year: string };
}) {
    const hasSearch = Boolean(filters.q);
    const hasScope = Boolean(filters.event || filters.class || filters.year);
    const eventGroups = results.data.reduce<
        {
            event: string;
            event_slug: string;
            starts_at: string | null;
            leaderboards: Leaderboard[];
        }[]
    >((groups, leaderboard) => {
        const existingGroup = groups.find(
            (group) => group.event_slug === leaderboard.event_slug,
        );

        if (existingGroup) {
            existingGroup.leaderboards.push(leaderboard);
        } else {
            groups.push({
                event: leaderboard.event,
                event_slug: leaderboard.event_slug,
                starts_at: leaderboard.starts_at,
                leaderboards: [leaderboard],
            });
        }

        return groups;
    }, []);

    return (
        <SiteLayout pageClassName="paddock-page results-page">
            <Head title="Race Results">
                <meta
                    name="description"
                    content="Browse classified motorsport results from completed events across Sri Lanka."
                />
            </Head>
            <main className="min-h-screen bg-[#e9e6dc] pb-16">
                <PublicPageHeading
                    eyebrow="Race archive · Classification"
                    title={
                        <>
                            RESULTS<span className="text-[#e6342b]">.</span>
                        </>
                    }
                    description="The finishing order, lap times and points from race weekends across Sri Lanka."
                    metrics={[
                        { label: 'Class leaderboards', value: results.total },
                    ]}
                >
                    <form
                        method="get"
                        action="/results"
                        role="search"
                        className="public-heading-search results-search flex max-w-xl flex-wrap items-center gap-2 border border-[#d8d4ca] bg-[#f8f6f0] p-2"
                    >
                        <label htmlFor="results-search" className="sr-only">
                            Search by racer, event or class
                        </label>
                        {filters.event ? (
                            <input
                                type="hidden"
                                name="event"
                                value={filters.event}
                            />
                        ) : null}
                        {filters.class ? (
                            <input
                                type="hidden"
                                name="class"
                                value={filters.class}
                            />
                        ) : null}
                        {filters.year ? (
                            <input
                                type="hidden"
                                name="year"
                                value={filters.year}
                            />
                        ) : null}
                        <div className="relative min-w-48 flex-1">
                            <Search
                                aria-hidden="true"
                                className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-[#747a77]"
                            />
                            <input
                                id="results-search"
                                type="search"
                                name="q"
                                defaultValue={filters.q}
                                placeholder="Search racer, event or class"
                                className="min-h-10 w-full border-0 bg-transparent py-2 pr-3 pl-9 text-sm text-[#111516] outline-none placeholder:text-[#8a8d87] focus:ring-0"
                            />
                        </div>
                        <SiteButton type="submit" variant="dark" size="sm">
                            Search
                        </SiteButton>
                        {hasSearch || hasScope ? (
                            <SiteActionLink
                                href="/results"
                                variant="outline"
                                size="sm"
                            >
                                Clear
                            </SiteActionLink>
                        ) : null}
                    </form>
                    {hasScope ? (
                        <p className="mt-1.5 text-[10px] font-semibold text-[#747a77]">
                            Showing linked results for{' '}
                            {results.data[0]?.event ?? 'the selected archive'}.
                        </p>
                    ) : null}
                </PublicPageHeading>

                <CinematicPageScene
                    eyebrow="Race classification"
                    title="Every finish tells a bigger story."
                    description="Read the timing, positions and points behind each published race classification."
                    image="https://images.unsplash.com/photo-1504215680853-026ed2a45def?auto=format&fit=crop&w=2200&q=85"
                    imageAlt="Race car moving through a circuit corner"
                />

                <section className="results-content mx-auto w-full px-5 pt-5 lg:px-8 lg:pt-6">
                    {results.data.length ? (
                        <section
                            aria-labelledby="classified-results-title"
                            className="mt-0"
                        >
                            <div className="mb-3 flex flex-wrap items-end justify-between gap-2">
                                <div>
                                    <p className="text-[10px] font-black tracking-[.2em] text-[#e8422b] uppercase">
                                        Timing desk
                                    </p>
                                    <h2
                                        id="classified-results-title"
                                        className="mt-1 text-lg font-black tracking-tight text-[#111516] sm:text-xl"
                                    >
                                        Leaderboards
                                    </h2>
                                </div>
                                <p className="text-[11px] font-bold text-[#747a77]">
                                    {results.total} class leaderboards
                                </p>
                            </div>

                            <div className="space-y-4">
                                {eventGroups.map((eventGroup) => (
                                    <section
                                        key={eventGroup.event_slug}
                                        className="results-event-group overflow-hidden border border-[#d8d4ca] bg-[#f8f6f0] shadow-[0_3px_12px_rgba(24,27,25,.035)]"
                                        aria-label={`${eventGroup.event} results`}
                                    >
                                        <header className="flex flex-wrap items-center justify-between gap-3 border-b border-[#dedbd2] bg-[#f1efe8] px-4 py-3 sm:px-5">
                                            <div className="flex min-w-0 items-center gap-3">
                                                <span
                                                    aria-hidden="true"
                                                    className="grid size-9 shrink-0 place-items-center rounded-lg bg-[#111516] text-[#f6c84f]"
                                                >
                                                    <Trophy className="size-4" />
                                                </span>
                                                <div className="min-w-0">
                                                    <Link
                                                        href={`/events/${eventGroup.event_slug}`}
                                                        className="block truncate text-base font-black tracking-tight text-[#111516] hover:text-[#c83221] sm:text-lg"
                                                    >
                                                        {eventGroup.event}
                                                    </Link>
                                                    <p className="mt-0.5 text-[10px] font-bold tracking-[.1em] text-[#747a77] uppercase">
                                                        {eventGroup.starts_at
                                                            ? new Date(
                                                                  eventGroup.starts_at,
                                                              ).getFullYear()
                                                            : 'Race archive'}
                                                        <span className="mx-1.5 text-[#c6c1b5]">
                                                            /
                                                        </span>
                                                        {
                                                            eventGroup
                                                                .leaderboards
                                                                .length
                                                        }{' '}
                                                        {eventGroup.leaderboards
                                                            .length === 1
                                                            ? 'class'
                                                            : 'classes'}{' '}
                                                        classified
                                                    </p>
                                                </div>
                                            </div>
                                            <Link
                                                href={`/events/${eventGroup.event_slug}`}
                                                className="shrink-0 text-xs font-black text-[#bd3428] underline decoration-[#bd3428]/30 underline-offset-4 hover:decoration-[#bd3428]"
                                            >
                                                Event details
                                            </Link>
                                        </header>

                                        <div className="grid gap-3 p-3 sm:p-4 md:grid-cols-2 xl:grid-cols-3">
                                            {eventGroup.leaderboards.map(
                                                (leaderboard, boardIndex) => (
                                                    <article
                                                        key={`${leaderboard.event_slug}-${leaderboard.race_class}-${boardIndex}`}
                                                        className="results-leaderboard min-w-0 overflow-hidden border border-[#e1ded6] bg-white"
                                                    >
                                                        <header className="flex items-center justify-between gap-2 border-b border-[#e1ded6] px-3 py-2.5">
                                                            <p className="text-[10px] font-black tracking-[.16em] text-[#747a77] uppercase">
                                                                Class
                                                                leaderboard
                                                            </p>
                                                            <span className="shrink-0 rounded-full bg-[#f6c84f] px-2.5 py-1.5 text-[9px] leading-none font-black text-[#111516]">
                                                                {
                                                                    leaderboard.race_class
                                                                }
                                                            </span>
                                                        </header>

                                                        <table className="w-full table-fixed text-left">
                                                            <thead>
                                                                <tr className="bg-[#eeece5] text-[9px] font-black tracking-[.13em] text-[#747a77] uppercase">
                                                                    <th
                                                                        scope="col"
                                                                        className="w-10 px-2 py-2"
                                                                    >
                                                                        Pos
                                                                    </th>
                                                                    <th
                                                                        scope="col"
                                                                        className="px-1.5 py-2"
                                                                    >
                                                                        Racer
                                                                    </th>
                                                                    <th
                                                                        scope="col"
                                                                        className="w-[68px] px-1.5 py-2"
                                                                    >
                                                                        Time
                                                                    </th>
                                                                    <th
                                                                        scope="col"
                                                                        className="w-[48px] px-2 py-2 text-right"
                                                                    >
                                                                        Pts
                                                                    </th>
                                                                </tr>
                                                            </thead>
                                                            <tbody className="divide-y divide-[#e5e2da]">
                                                                {leaderboard.results.map(
                                                                    (
                                                                        result,
                                                                    ) => (
                                                                        <tr
                                                                            key={`${result.profile.slug}-${result.position ?? result.result_status}`}
                                                                            className="align-middle hover:bg-white"
                                                                        >
                                                                            <td className="px-2 py-2">
                                                                                <span
                                                                                    className={`grid size-7 place-items-center rounded-full text-[10px] font-black tabular-nums ${result.position === 1 ? 'bg-[#e8422b] text-white' : result.position === 2 ? 'bg-[#d7d4cc] text-[#111516]' : result.position === 3 ? 'bg-[#e9d5c3] text-[#75451f]' : 'bg-white text-[#555d59]'}`}
                                                                                >
                                                                                    {result.position
                                                                                        ? String(
                                                                                              result.position,
                                                                                          ).padStart(
                                                                                              2,
                                                                                              '0',
                                                                                          )
                                                                                        : '—'}
                                                                                </span>
                                                                            </td>
                                                                            <td className="min-w-0 px-1.5 py-2">
                                                                                <Link
                                                                                    href={`/${result.profile.type === 'rider' ? 'riders' : 'drivers'}/${result.profile.slug}`}
                                                                                    className="block truncate text-xs leading-tight font-black text-[#111516] hover:text-[#c83221]"
                                                                                >
                                                                                    {
                                                                                        result
                                                                                            .profile
                                                                                            .name
                                                                                    }
                                                                                </Link>
                                                                                <div className="mt-0.5 flex flex-wrap items-center gap-1">
                                                                                    {result.race_number ? (
                                                                                        <span className="text-[9px] font-bold text-[#747a77]">
                                                                                            #
                                                                                            {
                                                                                                result.race_number
                                                                                            }
                                                                                        </span>
                                                                                    ) : null}
                                                                                    <span
                                                                                        className={`rounded-full px-1.5 py-0.5 text-[9px] leading-none font-black tracking-wide uppercase ${result.result_status === 'finished' ? 'bg-[#e9eee9] text-[#536557]' : 'bg-[#fbf2d5] text-[#725510]'}`}
                                                                                    >
                                                                                        {statusLabel(
                                                                                            result.result_status,
                                                                                        )}
                                                                                    </span>
                                                                                </div>
                                                                            </td>
                                                                            <td className="px-1.5 py-2 font-mono text-[10px] font-bold text-[#303735] tabular-nums">
                                                                                {result.time ||
                                                                                    '—'}
                                                                            </td>
                                                                            <td className="px-2 py-2 text-right text-xs font-black text-[#111516] tabular-nums">
                                                                                {result.points ??
                                                                                    '—'}
                                                                            </td>
                                                                        </tr>
                                                                    ),
                                                                )}
                                                            </tbody>
                                                        </table>
                                                    </article>
                                                ),
                                            )}
                                        </div>
                                    </section>
                                ))}
                            </div>

                            {results.links.length > 3 ? (
                                <nav
                                    aria-label="Results pages"
                                    className="results-panel mt-4 flex flex-wrap items-center justify-between gap-3 border border-[#d8d4ca] bg-[#f8f6f0] px-3 py-3"
                                >
                                    <span className="text-xs font-semibold text-[#747a77]">
                                        More race classifications
                                    </span>
                                    <div className="flex flex-wrap gap-1.5">
                                        {results.links.map((link, index) => (
                                            <Link
                                                key={index}
                                                preserveScroll
                                                href={link.url || '#'}
                                                aria-current={
                                                    link.active
                                                        ? 'page'
                                                        : undefined
                                                }
                                                aria-disabled={!link.url}
                                                className={`grid min-h-9 min-w-9 place-items-center rounded-lg border px-3 text-xs font-black transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#e8422b] ${link.active ? 'border-[#111516] bg-[#111516] text-white' : 'border-[#d8d4ca] bg-white text-[#555d59] hover:border-[#e8422b] hover:text-[#c83221]'} ${!link.url ? 'pointer-events-none opacity-40' : ''}`}
                                                dangerouslySetInnerHTML={{
                                                    __html: link.label,
                                                }}
                                            />
                                        ))}
                                    </div>
                                </nav>
                            ) : null}
                        </section>
                    ) : (
                        <div className="results-panel mt-5 grid gap-4 border border-[#d8d4ca] bg-[#f8f6f0] p-4 sm:grid-cols-[auto_1fr] sm:items-center sm:p-6">
                            <div className="results-mark grid size-14 place-items-center rounded-xl bg-[#111516] text-[#f6c84f]">
                                <Trophy aria-hidden="true" className="size-6" />
                            </div>
                            <div>
                                <p className="text-[10px] font-black tracking-[.18em] text-[#e8422b] uppercase">
                                    No classified sessions
                                </p>
                                <h2 className="mt-1 text-lg font-black tracking-tight text-[#111516] sm:text-xl">
                                    {hasSearch
                                        ? 'No results match this search'
                                        : hasScope
                                          ? 'No results in this linked selection'
                                          : 'No results have been published yet'}
                                </h2>
                                <p className="mt-2 max-w-xl text-sm leading-6 text-[#747a77]">
                                    {hasSearch
                                        ? 'Search by a different racer, event or class.'
                                        : 'Try searching for a racer, event or class. Completed race classifications will appear here when available.'}
                                </p>
                            </div>
                            <div className="flex flex-wrap gap-2 sm:col-start-2">
                                {hasSearch || hasScope ? (
                                    <SiteActionLink
                                        href="/results"
                                        variant="dark"
                                    >
                                        Clear search
                                    </SiteActionLink>
                                ) : null}
                                <SiteActionLink
                                    href="/events"
                                    variant="outline"
                                >
                                    Browse events
                                </SiteActionLink>
                            </div>
                        </div>
                    )}
                </section>
            </main>
        </SiteLayout>
    );
}
