import { useEffect, useState } from 'react';
import { Head } from '@inertiajs/react';
import { Radio, RefreshCw, Trophy } from 'lucide-react';
import SiteLayout from '@/components/site-layout';

type Score = {
    name: string;
    slug: string;
    profile_type: string;
    race_number: string | null;
    race_class: string | null;
    laps_completed: number;
    last_lap_milliseconds: number | null;
    best_lap_milliseconds: number | null;
    elapsed_milliseconds: number | null;
    penalty_milliseconds: number;
    result_status: string;
    position: number | null;
};
type Session = {
    id: number;
    name: string;
    format: 'lap_race' | 'timed_run';
    status: string;
    target_laps: number | null;
    updated_at: string | null;
    scores: Score[];
};
type Payload = {
    event: { title: string; slug: string };
    sessions: Session[];
    updated_at: string | null;
};

function formatMilliseconds(value: number | null): string {
    if (value === null) return '—';
    return `${Math.floor(value / 60000)}:${String(Math.floor((value % 60000) / 1000)).padStart(2, '0')}.${String(value % 1000).padStart(3, '0')}`;
}

export default function LiveScore({
    event,
    score_url,
}: {
    event: { title: string; slug: string };
    score_url: string;
}) {
    const [payload, setPayload] = useState<Payload | null>(null);
    const [updatedAt, setUpdatedAt] = useState<number | null>(null);
    const [error, setError] = useState(false);
    useEffect(() => {
        let active = true;
        let timer: ReturnType<typeof setInterval>;
        const refresh = async () => {
            try {
                const response = await fetch(score_url, {
                    headers: { Accept: 'application/json' },
                    cache: 'no-store',
                });
                if (!response.ok)
                    throw new Error('Live timing is unavailable.');
                const next = (await response.json()) as Payload;
                if (active) {
                    setPayload(next);
                    setUpdatedAt(Date.now());
                    setError(false);
                }
            } catch {
                if (active) setError(true);
            }
        };
        void refresh();
        timer = setInterval(() => {
            void refresh();
        }, 4000);
        return () => {
            active = false;
            clearInterval(timer);
        };
    }, [score_url]);

    const serverUpdatedAt = payload?.updated_at
        ? Date.parse(payload.updated_at)
        : null;
    const liveSession =
        payload?.sessions.some((session) => session.status === 'live') ?? false;
    const isStale =
        updatedAt === null ||
        (liveSession &&
            serverUpdatedAt !== null &&
            Date.now() - serverUpdatedAt > 12000);
    return (
        <SiteLayout pageClassName="paddock-page live-score-page">
            <Head title={`Live scoring · ${event.title}`}>
                <meta
                    name="description"
                    content={`Live race timing and provisional standings for ${event.title}.`}
                />
            </Head>
            <main className="mx-auto w-full max-w-[1336px] px-4 py-8 sm:px-7 lg:py-12">
                <a
                    href={`/events/${event.slug}`}
                    className="text-sm font-bold text-slate-600 hover:text-[#d6362a]"
                >
                    ← Event details
                </a>
                <div className="mt-5 flex flex-wrap items-end justify-between gap-4 border-b border-[#d8d4ca] pb-6">
                    <div>
                        <p className="text-xs font-black tracking-[.2em] text-[#d6362a] uppercase">
                            Race control · Live
                        </p>
                        <h1 className="mt-2 text-3xl font-black tracking-tight sm:text-5xl">
                            {event.title}
                        </h1>
                        <p className="mt-2 text-slate-600">
                            Live timing and provisional standings
                        </p>
                    </div>
                    <div className="flex items-center gap-2 rounded-full bg-[#172022] px-4 py-2 text-xs font-black text-white">
                        <span
                            className={`size-2 rounded-full ${error || isStale ? 'bg-amber-400' : 'animate-pulse bg-red-500'}`}
                        />
                        {error || isStale
                            ? 'Waiting for timing updates'
                            : 'LIVE · refreshes every 4 sec'}
                    </div>
                </div>
                {error ? (
                    <div
                        role="status"
                        className="mt-5 rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900"
                    >
                        Live scoring is temporarily unavailable. The board will
                        retry automatically.
                    </div>
                ) : null}
                {payload?.sessions.length ? (
                    <div className="mt-6 space-y-6">
                        {payload.sessions.map((session) => (
                            <section
                                key={session.id}
                                className="overflow-hidden rounded-2xl border border-[#d8d4ca] bg-white shadow-sm"
                            >
                                <header className="flex flex-wrap items-end justify-between gap-4 bg-[#172022] px-5 py-5 text-white sm:px-7">
                                    <div>
                                        <p className="text-[10px] font-black tracking-[.18em] text-[#f6c84f] uppercase">
                                            {session.format === 'lap_race'
                                                ? 'Lap race'
                                                : 'Timed run'}{' '}
                                            · {session.status}
                                        </p>
                                        <h2 className="mt-1 text-2xl font-black">
                                            {session.name}
                                        </h2>
                                    </div>
                                    <p className="text-xs text-white/60">
                                        Updated{' '}
                                        {session.updated_at
                                            ? new Date(
                                                  session.updated_at,
                                              ).toLocaleTimeString()
                                            : '—'}
                                    </p>
                                </header>
                                <div className="overflow-x-auto">
                                    <table className="w-full min-w-[650px] text-left text-sm">
                                        <thead className="bg-[#f2f0e9] text-[10px] font-black tracking-wider text-slate-500 uppercase">
                                            <tr>
                                                <th className="px-4 py-3">
                                                    Pos
                                                </th>
                                                <th className="px-4 py-3">
                                                    Racer
                                                </th>
                                                {session.format ===
                                                'lap_race' ? (
                                                    <th className="px-4 py-3">
                                                        Laps
                                                    </th>
                                                ) : null}
                                                <th className="px-4 py-3">
                                                    Last lap / time
                                                </th>
                                                <th className="px-4 py-3">
                                                    Best lap
                                                </th>
                                                <th className="px-4 py-3">
                                                    Penalty
                                                </th>
                                                <th className="px-4 py-3">
                                                    Status
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-black/5">
                                            {session.scores.map(
                                                (score, index) => (
                                                    <tr
                                                        key={`${session.id}-${score.slug}`}
                                                        className={
                                                            index === 0
                                                                ? 'bg-[#fff9e8]'
                                                                : ''
                                                        }
                                                    >
                                                        <td className="px-4 py-4 font-black">
                                                            {score.position
                                                                ? `P${score.position}`
                                                                : '—'}
                                                        </td>
                                                        <td className="px-4 py-4">
                                                            <a
                                                                className="font-black hover:text-[#d6362a]"
                                                                href={`/${score.profile_type === 'rider' ? 'riders' : 'drivers'}/${score.slug}`}
                                                            >
                                                                {score.race_number
                                                                    ? `#${score.race_number} `
                                                                    : ''}
                                                                {score.name}
                                                            </a>
                                                            <span className="mt-1 block text-xs text-slate-500">
                                                                {score.race_class ??
                                                                    'Open class'}
                                                            </span>
                                                        </td>
                                                        {session.format ===
                                                        'lap_race' ? (
                                                            <td className="px-4 py-4 font-bold">
                                                                {
                                                                    score.laps_completed
                                                                }
                                                                {session.target_laps
                                                                    ? ` / ${session.target_laps}`
                                                                    : ''}
                                                            </td>
                                                        ) : null}
                                                        <td className="px-4 py-4 font-mono font-bold">
                                                            {formatMilliseconds(
                                                                session.format ===
                                                                    'lap_race'
                                                                    ? score.last_lap_milliseconds
                                                                    : score.elapsed_milliseconds,
                                                            )}
                                                        </td>
                                                        <td className="px-4 py-4 font-mono">
                                                            {formatMilliseconds(
                                                                score.best_lap_milliseconds,
                                                            )}
                                                        </td>
                                                        <td className="px-4 py-4">
                                                            {score.penalty_milliseconds
                                                                ? `+${formatMilliseconds(score.penalty_milliseconds)}`
                                                                : '—'}
                                                        </td>
                                                        <td className="px-4 py-4">
                                                            <span className="rounded-full bg-[#ebe9e2] px-2.5 py-1 text-[10px] font-black uppercase">
                                                                {
                                                                    score.result_status
                                                                }
                                                            </span>
                                                        </td>
                                                    </tr>
                                                ),
                                            )}
                                        </tbody>
                                    </table>
                                </div>
                                {session.status === 'finalized' ? (
                                    <div className="flex items-center gap-2 border-t border-black/5 px-5 py-4 text-sm font-bold text-emerald-800">
                                        <Trophy size={16} />
                                        Official results have been published.
                                    </div>
                                ) : null}
                            </section>
                        ))}
                    </div>
                ) : (
                    <div className="mt-8 rounded-2xl border border-dashed border-[#d8d4ca] bg-white p-10 text-center">
                        <Radio className="mx-auto text-[#d6362a]" />
                        <h2 className="mt-3 text-xl font-black">
                            No timing signal yet
                        </h2>
                        <p className="mt-2 text-sm text-slate-600">
                            The live board will appear when event control starts
                            a scoring session.
                        </p>
                        <RefreshCw
                            className="mx-auto mt-4 text-slate-400"
                            size={16}
                        />
                    </div>
                )}
            </main>
        </SiteLayout>
    );
}
