import { Form, Head, Link } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import ScoringSessionController from '@/actions/App/Http/Controllers/ScoringSessionController';
import StandPhotoController from '@/actions/App/Http/Controllers/StandPhotoController';
import InputError from '@/components/input-error';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { dashboard } from '@/routes';

type SessionPlayer = {
    id: number;
    targets_hit: number;
    targets_attempted: number;
    user: {
        id: number;
        name: string;
        email: string;
    };
};

type SessionLocation = {
    name: string;
    town: string;
    region: string;
} | null;

type SessionStand = {
    id: number;
    stand_id: number;
    stand_name: string;
    position_label: string | null;
    shooting_mode: string;
    scoring_type: string;
    target_count: number;
    clay_count: number;
};

type StandQueueItem = {
    id: number;
    stand_name: string;
    position_label: string | null;
    shooting_mode: string;
    scoring_type: string;
    target_count: number;
    is_complete: boolean;
};

type AvailableStand = {
    id: number;
    name: string;
    position_label: string | null;
    location_name: string;
    clay_count: number;
};

type Target = {
    label: string;
    type: string;
};

type LiveEntry = {
    hits: number;
    shots_taken: number;
};

type Photo = {
    id: number;
    url: string;
    caption: string | null;
    uploaded_by: string;
    uploaded_at: string | null;
};

type Session = {
    id: number;
    name: string;
    status: string;
    notes: string | null;
    shot_at: string | null;
    default_shooting_mode: string | null;
    default_scoring_type: string | null;
    default_target_count: number | null;
    location: SessionLocation;
    players: SessionPlayer[];
    stands: SessionStand[];
};

type Scores = Record<number, Record<string, LiveEntry>>;

type PlayerOption = {
    id: number;
    name: string;
    email: string;
};

function formatMode(mode: string): string {
    switch (mode) {
        case 'report_pairs':
            return 'Report Pairs';
        case 'true_pairs':
            return 'True Pairs';
        default:
            return 'Singles';
    }
}

function formatScoringType(scoringType: string): string {
    return scoringType === 'per_stand' ? 'Stand total' : 'Per clay';
}

function formatDate(date: string | null): string {
    if (!date) {
        return 'Just now';
    }

    return new Intl.DateTimeFormat('en-GB', {
        day: 'numeric',
        month: 'short',
        year: 'numeric',
    }).format(new Date(date));
}

function toDateTimeLocal(date: string | null): string {
    if (!date) {
        return '';
    }

    const parsedDate = new Date(date);
    const year = String(parsedDate.getFullYear());
    const month = String(parsedDate.getMonth() + 1).padStart(2, '0');
    const day = String(parsedDate.getDate()).padStart(2, '0');
    const hours = String(parsedDate.getHours()).padStart(2, '0');
    const minutes = String(parsedDate.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

export default function LiveScoring({
    session,
    currentStand,
    currentScores: initialScores,
    currentStandTargets,
    standQueue,
    availableStands,
    standPhotos,
    allPlayers,
}: {
    session: Session;
    currentStand: SessionStand | null;
    currentScores: Scores;
    currentStandTargets: Target[];
    standQueue: StandQueueItem[];
    availableStands: AvailableStand[];
    standPhotos: Photo[];
    allPlayers: PlayerOption[];
}) {
    const [scores, setScores] = useState<Scores>(initialScores);
    const [selectedStandId, setSelectedStandId] = useState<number>(
        availableStands[0]?.id ?? 0,
    );

    const nextStandId = useMemo(() => {
        if (!currentStand) {
            return null;
        }

        const currentIndex = standQueue.findIndex(
            (stand) => stand.id === currentStand.id,
        );

        if (currentIndex === -1 || currentIndex === standQueue.length - 1) {
            return null;
        }

        return standQueue[currentIndex + 1].id;
    }, [currentStand, standQueue]);

    const updateEntry = (
        playerId: number,
        clayLabel: string,
        maxShots: number,
        action: 'hit' | 'miss' | 'undo_hit' | 'undo_miss',
    ) => {
        setScores((current) => {
            const playerScores = current[playerId] ?? {};
            const existingEntry = playerScores[clayLabel] ?? {
                hits: 0,
                shots_taken: 0,
            };
            const nextEntry = { ...existingEntry };
            const misses = nextEntry.shots_taken - nextEntry.hits;

            if (action === 'hit' && nextEntry.shots_taken < maxShots) {
                nextEntry.hits += 1;
                nextEntry.shots_taken += 1;
            }

            if (action === 'miss' && nextEntry.shots_taken < maxShots) {
                nextEntry.shots_taken += 1;
            }

            if (action === 'undo_hit' && nextEntry.hits > 0) {
                nextEntry.hits -= 1;
                nextEntry.shots_taken -= 1;
            }

            if (action === 'undo_miss' && misses > 0) {
                nextEntry.shots_taken -= 1;
            }

            return {
                ...current,
                [playerId]: {
                    ...playerScores,
                    [clayLabel]: nextEntry,
                },
            };
        });
    };

    return (
        <>
            <Head title={`${session.name} Live Scoring`} />

            <div className="space-y-6 p-4 md:p-6">
                <div className="space-y-4 rounded-3xl border border-border/70 bg-[radial-gradient(circle_at_top_left,_rgba(192,139,54,0.18),_transparent_38%),linear-gradient(135deg,_rgba(37,52,47,0.98),_rgba(17,24,22,0.94))] p-5 text-white shadow-sm md:p-6">
                    <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
                        <div className="space-y-2">
                            <h1 className="text-3xl font-semibold tracking-tight md:text-4xl">
                                Live scoring
                            </h1>
                            <p className="text-sm text-white/75 md:text-base">
                                {session.name}
                                {session.location
                                    ? ` · ${session.location.name} · ${session.location.town}, ${session.location.region}`
                                    : ' · Location will be set by the first stand you add'}
                            </p>
                        </div>
                        <div className="flex flex-wrap gap-2">
                            <Badge className="bg-white/10 text-white hover:bg-white/10">
                                {session.players.length} shooters
                            </Badge>
                            <Badge className="bg-white/10 text-white hover:bg-white/10">
                                {standQueue.length} stands added
                            </Badge>
                            <Badge className="bg-white/10 text-white hover:bg-white/10">
                                {session.status === 'completed'
                                    ? 'Completed'
                                    : 'In progress'}
                            </Badge>
                        </div>
                    </div>
                    <p className="max-w-3xl text-sm leading-6 text-white/75">
                        Add the next stand when you arrive, then choose whether
                        to score each clay separately or record one combined
                        stand total.
                    </p>
                </div>

                <div className="grid gap-6 xl:grid-cols-[0.78fr_1.22fr]">
                    <div className="space-y-6">
                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Session setup</CardTitle>
                                <CardDescription>
                                    Adjust the squad or the default stand
                                    pattern at any point. New stands will use
                                    these defaults.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <Form
                                    {...ScoringSessionController.updateSetup.form(
                                        session.id,
                                    )}
                                    className="space-y-4"
                                >
                                    {({ processing, errors }) => (
                                        <>
                                            <div className="grid gap-4">
                                                <div className="grid gap-2">
                                                    <label
                                                        htmlFor="live-setup-name"
                                                        className="text-sm font-medium"
                                                    >
                                                        Session name
                                                    </label>
                                                    <input
                                                        id="live-setup-name"
                                                        name="name"
                                                        defaultValue={
                                                            session.name
                                                        }
                                                        className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                    />
                                                    <InputError
                                                        message={errors.name}
                                                    />
                                                </div>
                                                <div className="grid gap-2">
                                                    <label
                                                        htmlFor="live-setup-shot-at"
                                                        className="text-sm font-medium"
                                                    >
                                                        Shot date and time
                                                    </label>
                                                    <input
                                                        id="live-setup-shot-at"
                                                        name="shot_at"
                                                        type="datetime-local"
                                                        defaultValue={toDateTimeLocal(
                                                            session.shot_at,
                                                        )}
                                                        className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                    />
                                                    <InputError
                                                        message={
                                                            errors.shot_at
                                                        }
                                                    />
                                                </div>
                                            </div>

                                            <div className="grid gap-4 sm:grid-cols-3">
                                                <div className="grid gap-2">
                                                    <label className="text-sm font-medium">
                                                        Default shooting mode
                                                    </label>
                                                    <select
                                                        name="default_shooting_mode"
                                                        defaultValue={
                                                            session.default_shooting_mode ??
                                                            'singles'
                                                        }
                                                        className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                    >
                                                        <option value="singles">
                                                            Singles
                                                        </option>
                                                        <option value="report_pairs">
                                                            Report Pairs
                                                        </option>
                                                        <option value="true_pairs">
                                                            True Pairs
                                                        </option>
                                                    </select>
                                                    <InputError
                                                        message={
                                                            errors.default_shooting_mode
                                                        }
                                                    />
                                                </div>
                                                <div className="grid gap-2">
                                                    <label className="text-sm font-medium">
                                                        Default score by
                                                    </label>
                                                    <select
                                                        name="default_scoring_type"
                                                        defaultValue={
                                                            session.default_scoring_type ??
                                                            'per_clay'
                                                        }
                                                        className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                    >
                                                        <option value="per_clay">
                                                            Each clay
                                                        </option>
                                                        <option value="per_stand">
                                                            Whole stand total
                                                        </option>
                                                    </select>
                                                    <InputError
                                                        message={
                                                            errors.default_scoring_type
                                                        }
                                                    />
                                                </div>
                                                <div className="grid gap-2">
                                                    <label className="text-sm font-medium">
                                                        Default targets per clay
                                                    </label>
                                                    <input
                                                        type="number"
                                                        name="default_target_count"
                                                        min={1}
                                                        max={30}
                                                        defaultValue={
                                                            session.default_target_count ??
                                                            30
                                                        }
                                                        className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                    />
                                                    <InputError
                                                        message={
                                                            errors.default_target_count
                                                        }
                                                    />
                                                </div>
                                            </div>

                                            <div className="grid gap-3">
                                                <div>
                                                    <p className="text-sm font-medium">
                                                        Players
                                                    </p>
                                                    <p className="text-sm text-muted-foreground">
                                                        Update the squad if
                                                        someone joins late or
                                                        leaves the round.
                                                    </p>
                                                </div>
                                                <div className="grid gap-3">
                                                    {allPlayers.map((player) => (
                                                        <label
                                                            key={`live-setup-${player.id}`}
                                                            className="flex items-start gap-3 rounded-2xl border border-border/70 bg-muted/15 p-4"
                                                        >
                                                            <input
                                                                type="checkbox"
                                                                name="player_ids[]"
                                                                value={player.id}
                                                                defaultChecked={session.players.some(
                                                                    (
                                                                        sessionPlayer,
                                                                    ) =>
                                                                        sessionPlayer
                                                                            .user
                                                                            .id ===
                                                                        player.id,
                                                                )}
                                                                className="mt-1 size-4 rounded border-border text-primary focus:ring-primary"
                                                            />
                                                            <div className="min-w-0">
                                                                <p className="font-medium">
                                                                    {player.name}
                                                                </p>
                                                                <p className="truncate text-sm text-muted-foreground">
                                                                    {player.email}
                                                                </p>
                                                            </div>
                                                        </label>
                                                    ))}
                                                </div>
                                                <InputError
                                                    message={errors.player_ids}
                                                />
                                            </div>

                                            <Button disabled={processing}>
                                                Save setup
                                            </Button>
                                        </>
                                    )}
                                </Form>
                            </CardContent>
                        </Card>

                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Add next stand</CardTitle>
                                <CardDescription>
                                    Live setup stays light. Pick the next stand
                                    only when you are ready to shoot it.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <Form
                                    {...ScoringSessionController.storeLiveStand.form(
                                        session.id,
                                    )}
                                    className="space-y-4"
                                >
                                    {({ processing, errors }) => (
                                        <>
                                            <div className="grid gap-2">
                                                <label
                                                    htmlFor="live-stand-id"
                                                    className="text-sm font-medium"
                                                >
                                                    Stand
                                                </label>
                                                <select
                                                    id="live-stand-id"
                                                    name="stand_id"
                                                    value={selectedStandId}
                                                    onChange={(event) =>
                                                        setSelectedStandId(
                                                            Number(
                                                                event.target
                                                                    .value,
                                                            ),
                                                        )
                                                    }
                                                    className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                >
                                                    {availableStands.length ===
                                                    0 ? (
                                                        <option value={0}>
                                                            No more stands available
                                                        </option>
                                                    ) : (
                                                        availableStands.map(
                                                            (stand) => (
                                                                <option
                                                                    key={stand.id}
                                                                    value={stand.id}
                                                                >
                                                                    {
                                                                        stand.location_name
                                                                    }{' '}
                                                                    ·{' '}
                                                                    {stand.position_label
                                                                        ? `Stand ${stand.position_label}`
                                                                        : stand.name}{' '}
                                                                    ·{' '}
                                                                    {
                                                                        stand.clay_count
                                                                    }{' '}
                                                                    clays
                                                                </option>
                                                            ),
                                                        )
                                                    )}
                                                </select>
                                                <InputError
                                                    message={errors.stand_id}
                                                />
                                            </div>

                                            <div className="grid gap-4 sm:grid-cols-3">
                                                <div className="grid gap-2">
                                                    <label className="text-sm font-medium">
                                                        Shooting mode
                                                    </label>
                                                    <select
                                                        name="shooting_mode"
                                                        defaultValue={
                                                            session.default_shooting_mode ??
                                                            'singles'
                                                        }
                                                        className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                    >
                                                        <option value="singles">
                                                            Singles
                                                        </option>
                                                        <option value="report_pairs">
                                                            Report Pairs
                                                        </option>
                                                        <option value="true_pairs">
                                                            True Pairs
                                                        </option>
                                                    </select>
                                                    <InputError
                                                        message={
                                                            errors.shooting_mode
                                                        }
                                                    />
                                                </div>
                                                <div className="grid gap-2">
                                                    <label className="text-sm font-medium">
                                                        Score by
                                                    </label>
                                                    <select
                                                        name="scoring_type"
                                                        defaultValue={
                                                            session.default_scoring_type ??
                                                            'per_clay'
                                                        }
                                                        className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                    >
                                                        <option value="per_clay">
                                                            Each clay
                                                        </option>
                                                        <option value="per_stand">
                                                            Whole stand total
                                                        </option>
                                                    </select>
                                                    <InputError
                                                        message={
                                                            errors.scoring_type
                                                        }
                                                    />
                                                </div>
                                                <div className="grid gap-2">
                                                    <label className="text-sm font-medium">
                                                        Shots per clay
                                                    </label>
                                                    <input
                                                        type="number"
                                                        name="target_count"
                                                        min={1}
                                                        max={30}
                                                        defaultValue={
                                                            session.default_target_count ??
                                                            30
                                                        }
                                                        className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                    />
                                                    <InputError
                                                        message={
                                                            errors.target_count
                                                        }
                                                    />
                                                </div>
                                            </div>

                                            <Button
                                                disabled={
                                                    processing ||
                                                    availableStands.length === 0
                                                }
                                                className="w-full"
                                            >
                                                Add stand to live round
                                            </Button>
                                        </>
                                    )}
                                </Form>
                            </CardContent>
                        </Card>

                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Stand queue</CardTitle>
                                <CardDescription>
                                    Jump between added stands or save and move
                                    forward in order.
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-3">
                                {standQueue.length > 0 ? (
                                    standQueue.map((stand) => (
                                        <Link
                                            key={stand.id}
                                            href={ScoringSessionController.live(
                                                session.id,
                                                {
                                                    query: {
                                                        stand: stand.id,
                                                    },
                                                },
                                            )}
                                            className="block rounded-2xl border border-border/70 bg-muted/15 p-4 transition-colors hover:bg-muted/25"
                                        >
                                            <div className="flex items-center justify-between gap-3">
                                                <div>
                                                    <p className="font-medium">
                                                        {stand.stand_name}
                                                    </p>
                                                    <p className="text-sm text-muted-foreground">
                                                        {stand.position_label
                                                            ? `Position ${stand.position_label}`
                                                            : 'No position set'}{' '}
                                                        ·{' '}
                                                        {formatMode(
                                                            stand.shooting_mode,
                                                        )}{' '}
                                                        ·{' '}
                                                        {formatScoringType(
                                                            stand.scoring_type,
                                                        )}
                                                    </p>
                                                </div>
                                                <Badge
                                                    className={
                                                        stand.is_complete
                                                            ? 'bg-emerald-600/10 text-emerald-700 hover:bg-emerald-600/10 dark:text-emerald-300'
                                                            : 'bg-amber-500/10 text-amber-700 hover:bg-amber-500/10 dark:text-amber-300'
                                                    }
                                                >
                                                    {stand.is_complete
                                                        ? 'Done'
                                                        : 'Current'}
                                                </Badge>
                                            </div>
                                        </Link>
                                    ))
                                ) : (
                                    <p className="rounded-2xl border border-dashed border-border/70 bg-muted/15 p-4 text-sm text-muted-foreground">
                                        No stands added yet. Start by picking
                                        the first stand above.
                                    </p>
                                )}
                            </CardContent>
                        </Card>
                    </div>

                    <div className="space-y-6">
                        {currentStand ? (
                            <>
                                <Card className="border-border/70">
                                    <CardHeader>
                                        <CardTitle>
                                            {currentStand.stand_name}
                                        </CardTitle>
                                        <CardDescription>
                                            {currentStand.position_label
                                                ? `Position ${currentStand.position_label}`
                                                : 'No position set'}{' '}
                                            ·{' '}
                                            {formatMode(
                                                currentStand.shooting_mode,
                                            )}{' '}
                                            ·{' '}
                                            {formatScoringType(
                                                currentStand.scoring_type,
                                            )}{' '}
                                            · {currentStand.target_count} shots
                                            per clay
                                        </CardDescription>
                                    </CardHeader>
                                    <CardContent>
                                        <Form
                                            {...ScoringSessionController.updateLive.form(
                                                session.id,
                                            )}
                                            className="space-y-6"
                                        >
                                            {({ processing, errors }) => (
                                                <>
                                                    <input
                                                        type="hidden"
                                                        name="session_stand_id"
                                                        value={currentStand.id}
                                                    />
                                                    <input
                                                        type="hidden"
                                                        name="status"
                                                        value={session.status}
                                                    />
                                                    <input
                                                        type="hidden"
                                                        name="notes"
                                                        value={
                                                            session.notes ?? ''
                                                        }
                                                    />

                                                    {session.players.map(
                                                        (player) => {
                                                            const standEntry =
                                                                scores[
                                                                    player.id
                                                                ]?.[
                                                                    '__stand_total__'
                                                                ] ?? {
                                                                    hits: 0,
                                                                    shots_taken:
                                                                        0,
                                                                };
                                                            const standMaxShots =
                                                                currentStand.target_count *
                                                                currentStand.clay_count;

                                                            return (
                                                                <div
                                                                    key={
                                                                        player.id
                                                                    }
                                                                    className="space-y-4 rounded-3xl border border-border/70 bg-muted/15 p-4 md:p-5"
                                                                >
                                                                    <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                                                                        <div>
                                                                            <p className="font-semibold">
                                                                                {
                                                                                    player
                                                                                        .user
                                                                                        .name
                                                                                }
                                                                            </p>
                                                                            <p className="text-sm text-muted-foreground">
                                                                                {
                                                                                    player
                                                                                        .user
                                                                                        .email
                                                                                }
                                                                            </p>
                                                                        </div>
                                                                        <Badge variant="secondary">
                                                                            {
                                                                                player.targets_hit
                                                                            }
                                                                            /
                                                                            {
                                                                                player.targets_attempted
                                                                            }{' '}
                                                                            overall
                                                                        </Badge>
                                                                    </div>

                                                                    {currentStand.scoring_type ===
                                                                    'per_stand' ? (
                                                                        <div className="rounded-2xl border border-border/70 bg-background p-4">
                                                                            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                                                                                <div>
                                                                                    <p className="text-lg font-semibold">
                                                                                        Stand total
                                                                                    </p>
                                                                                    <p className="text-sm text-muted-foreground">
                                                                                        Combined score for all{' '}
                                                                                        {
                                                                                            currentStand.clay_count
                                                                                        }{' '}
                                                                                        clays on this stand.
                                                                                    </p>
                                                                                </div>
                                                                                <div className="flex flex-wrap gap-2 text-sm">
                                                                                    <Badge variant="secondary">
                                                                                        {
                                                                                            standEntry.hits
                                                                                        }{' '}
                                                                                        hit
                                                                                    </Badge>
                                                                                    <Badge variant="secondary">
                                                                                        {standEntry.shots_taken -
                                                                                            standEntry.hits}{' '}
                                                                                        miss
                                                                                    </Badge>
                                                                                    <Badge
                                                                                        className={
                                                                                            standEntry.shots_taken >=
                                                                                            standMaxShots
                                                                                                ? 'bg-emerald-600/10 text-emerald-700 hover:bg-emerald-600/10 dark:text-emerald-300'
                                                                                                : 'bg-amber-500/10 text-amber-700 hover:bg-amber-500/10 dark:text-amber-300'
                                                                                        }
                                                                                    >
                                                                                        {
                                                                                            standEntry.shots_taken
                                                                                        }
                                                                                        /
                                                                                        {
                                                                                            standMaxShots
                                                                                        }
                                                                                    </Badge>
                                                                                </div>
                                                                            </div>

                                                                            <input
                                                                                type="hidden"
                                                                                name={`stand_totals[${player.id}][hits]`}
                                                                                value={
                                                                                    standEntry.hits
                                                                                }
                                                                            />
                                                                            <input
                                                                                type="hidden"
                                                                                name={`stand_totals[${player.id}][shots_taken]`}
                                                                                value={
                                                                                    standEntry.shots_taken
                                                                                }
                                                                            />

                                                                            <div className="mt-4 grid gap-3 sm:grid-cols-2">
                                                                                <Button
                                                                                    type="button"
                                                                                    className="h-16 rounded-2xl bg-emerald-600 text-lg font-semibold text-white hover:bg-emerald-700"
                                                                                    disabled={
                                                                                        standEntry.shots_taken >=
                                                                                        standMaxShots
                                                                                    }
                                                                                    onClick={() =>
                                                                                        updateEntry(
                                                                                            player.id,
                                                                                            '__stand_total__',
                                                                                            standMaxShots,
                                                                                            'hit',
                                                                                        )
                                                                                    }
                                                                                >
                                                                                    Hit
                                                                                </Button>
                                                                                <Button
                                                                                    type="button"
                                                                                    variant="secondary"
                                                                                    className="h-16 rounded-2xl text-lg font-semibold"
                                                                                    disabled={
                                                                                        standEntry.shots_taken >=
                                                                                        standMaxShots
                                                                                    }
                                                                                    onClick={() =>
                                                                                        updateEntry(
                                                                                            player.id,
                                                                                            '__stand_total__',
                                                                                            standMaxShots,
                                                                                            'miss',
                                                                                        )
                                                                                    }
                                                                                >
                                                                                    Miss
                                                                                </Button>
                                                                                <Button
                                                                                    type="button"
                                                                                    variant="outline"
                                                                                    className="h-12 rounded-2xl text-sm font-medium"
                                                                                    disabled={
                                                                                        standEntry.hits ===
                                                                                        0
                                                                                    }
                                                                                    onClick={() =>
                                                                                        updateEntry(
                                                                                            player.id,
                                                                                            '__stand_total__',
                                                                                            standMaxShots,
                                                                                            'undo_hit',
                                                                                        )
                                                                                    }
                                                                                >
                                                                                    Undo hit
                                                                                </Button>
                                                                                <Button
                                                                                    type="button"
                                                                                    variant="outline"
                                                                                    className="h-12 rounded-2xl text-sm font-medium"
                                                                                    disabled={
                                                                                        standEntry.shots_taken -
                                                                                            standEntry.hits ===
                                                                                        0
                                                                                    }
                                                                                    onClick={() =>
                                                                                        updateEntry(
                                                                                            player.id,
                                                                                            '__stand_total__',
                                                                                            standMaxShots,
                                                                                            'undo_miss',
                                                                                        )
                                                                                    }
                                                                                >
                                                                                    Undo miss
                                                                                </Button>
                                                                            </div>
                                                                        </div>
                                                                    ) : (
                                                                        <div className="grid gap-4">
                                                                            {currentStandTargets.map(
                                                                                (
                                                                                    target,
                                                                                ) => {
                                                                                    const entry =
                                                                                        scores[
                                                                                            player
                                                                                                .id
                                                                                        ]?.[
                                                                                            target
                                                                                                .label
                                                                                        ] ?? {
                                                                                            hits: 0,
                                                                                            shots_taken:
                                                                                                0,
                                                                                        };
                                                                                    const misses =
                                                                                        entry.shots_taken -
                                                                                        entry.hits;
                                                                                    const isComplete =
                                                                                        entry.shots_taken >=
                                                                                        currentStand.target_count;

                                                                                    return (
                                                                                        <div
                                                                                            key={`${player.id}-${target.label}`}
                                                                                            className="rounded-2xl border border-border/70 bg-background p-4"
                                                                                        >
                                                                                            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                                                                                                <div>
                                                                                                    <p className="text-lg font-semibold">
                                                                                                        Clay{' '}
                                                                                                        {
                                                                                                            target.label
                                                                                                        }
                                                                                                    </p>
                                                                                                    <p className="text-sm text-muted-foreground">
                                                                                                        {
                                                                                                            target.type
                                                                                                        }
                                                                                                    </p>
                                                                                                </div>
                                                                                                <div className="flex flex-wrap gap-2 text-sm">
                                                                                                    <Badge variant="secondary">
                                                                                                        {
                                                                                                            entry.hits
                                                                                                        }{' '}
                                                                                                        hit
                                                                                                    </Badge>
                                                                                                    <Badge variant="secondary">
                                                                                                        {
                                                                                                            misses
                                                                                                        }{' '}
                                                                                                        miss
                                                                                                    </Badge>
                                                                                                    <Badge
                                                                                                        className={
                                                                                                            isComplete
                                                                                                                ? 'bg-emerald-600/10 text-emerald-700 hover:bg-emerald-600/10 dark:text-emerald-300'
                                                                                                                : 'bg-amber-500/10 text-amber-700 hover:bg-amber-500/10 dark:text-amber-300'
                                                                                                        }
                                                                                                    >
                                                                                                        {
                                                                                                            entry.shots_taken
                                                                                                        }
                                                                                                        /
                                                                                                        {
                                                                                                            currentStand.target_count
                                                                                                        }
                                                                                                    </Badge>
                                                                                                </div>
                                                                                            </div>

                                                                                            <input
                                                                                                type="hidden"
                                                                                                name={`scores[${player.id}][${target.label}][hits]`}
                                                                                                value={
                                                                                                    entry.hits
                                                                                                }
                                                                                            />
                                                                                            <input
                                                                                                type="hidden"
                                                                                                name={`scores[${player.id}][${target.label}][shots_taken]`}
                                                                                                value={
                                                                                                    entry.shots_taken
                                                                                                }
                                                                                            />

                                                                                            <div className="mt-4 grid gap-3 sm:grid-cols-2">
                                                                                                <Button
                                                                                                    type="button"
                                                                                                    className="h-16 rounded-2xl bg-emerald-600 text-lg font-semibold text-white hover:bg-emerald-700"
                                                                                                    disabled={
                                                                                                        isComplete
                                                                                                    }
                                                                                                    onClick={() =>
                                                                                                        updateEntry(
                                                                                                            player.id,
                                                                                                            target.label,
                                                                                                            currentStand.target_count,
                                                                                                            'hit',
                                                                                                        )
                                                                                                    }
                                                                                                >
                                                                                                    Hit
                                                                                                </Button>
                                                                                                <Button
                                                                                                    type="button"
                                                                                                    variant="secondary"
                                                                                                    className="h-16 rounded-2xl text-lg font-semibold"
                                                                                                    disabled={
                                                                                                        isComplete
                                                                                                    }
                                                                                                    onClick={() =>
                                                                                                        updateEntry(
                                                                                                            player.id,
                                                                                                            target.label,
                                                                                                            currentStand.target_count,
                                                                                                            'miss',
                                                                                                        )
                                                                                                    }
                                                                                                >
                                                                                                    Miss
                                                                                                </Button>
                                                                                                <Button
                                                                                                    type="button"
                                                                                                    variant="outline"
                                                                                                    className="h-12 rounded-2xl text-sm font-medium"
                                                                                                    disabled={
                                                                                                        entry.hits ===
                                                                                                        0
                                                                                                    }
                                                                                                    onClick={() =>
                                                                                                        updateEntry(
                                                                                                            player.id,
                                                                                                            target.label,
                                                                                                            currentStand.target_count,
                                                                                                            'undo_hit',
                                                                                                        )
                                                                                                    }
                                                                                                >
                                                                                                    Undo hit
                                                                                                </Button>
                                                                                                <Button
                                                                                                    type="button"
                                                                                                    variant="outline"
                                                                                                    className="h-12 rounded-2xl text-sm font-medium"
                                                                                                    disabled={
                                                                                                        misses ===
                                                                                                        0
                                                                                                    }
                                                                                                    onClick={() =>
                                                                                                        updateEntry(
                                                                                                            player.id,
                                                                                                            target.label,
                                                                                                            currentStand.target_count,
                                                                                                            'undo_miss',
                                                                                                        )
                                                                                                    }
                                                                                                >
                                                                                                    Undo miss
                                                                                                </Button>
                                                                                            </div>
                                                                                        </div>
                                                                                    );
                                                                                },
                                                                            )}
                                                                        </div>
                                                                    )}
                                                                </div>
                                                            );
                                                        },
                                                    )}

                                                    <div className="sticky bottom-3 z-20 flex flex-col gap-3 rounded-3xl border border-border/70 bg-background/95 p-4 shadow-lg backdrop-blur sm:flex-row">
                                                        <Button
                                                            disabled={processing}
                                                            className="h-14 flex-1 rounded-2xl text-base font-semibold"
                                                        >
                                                            Save stand
                                                        </Button>
                                                        {nextStandId ? (
                                                            <Button
                                                                type="submit"
                                                                name="next_stand_id"
                                                                value={
                                                                    nextStandId
                                                                }
                                                                variant="secondary"
                                                                disabled={
                                                                    processing
                                                                }
                                                                className="h-14 rounded-2xl px-5 text-base font-semibold"
                                                            >
                                                                Save and next stand
                                                            </Button>
                                                        ) : null}
                                                        <Button
                                                            type="submit"
                                                            name="status"
                                                            value="completed"
                                                            variant="secondary"
                                                            disabled={processing}
                                                            className="h-14 rounded-2xl px-5 text-base font-semibold"
                                                        >
                                                            Save and finish round
                                                        </Button>
                                                        <Link
                                                            href={ScoringSessionController.liveSetup()}
                                                            className="inline-flex h-14 items-center justify-center rounded-2xl border border-border px-4 text-base font-medium"
                                                        >
                                                            Back to live setup
                                                        </Link>
                                                    </div>

                                                    <InputError
                                                        message={
                                                            errors.session_stand_id
                                                        }
                                                    />
                                                    <InputError
                                                        message={
                                                            errors.stand_totals
                                                        }
                                                    />
                                                </>
                                            )}
                                        </Form>
                                    </CardContent>
                                </Card>

                                <Card className="border-border/70">
                                    <CardHeader>
                                        <CardTitle>Stand reference photos</CardTitle>
                                        <CardDescription>
                                            Upload member photos for this stand
                                            to show clay positions and visual
                                            lines.
                                        </CardDescription>
                                    </CardHeader>
                                    <CardContent className="space-y-4">
                                        {standPhotos.length > 0 ? (
                                            <div className="flex gap-3 overflow-x-auto pb-2">
                                                {standPhotos.map((photo) => (
                                                    <div
                                                        key={photo.id}
                                                        className="min-w-[220px] max-w-[220px] overflow-hidden rounded-2xl border border-border/70 bg-muted/15"
                                                    >
                                                        <img
                                                            src={photo.url}
                                                            alt={
                                                                photo.caption ??
                                                                `${currentStand.stand_name} reference`
                                                            }
                                                            className="h-40 w-full object-cover"
                                                        />
                                                        <div className="space-y-1 p-3 text-sm">
                                                            <p className="font-medium">
                                                                {photo.caption ??
                                                                    'Member reference photo'}
                                                            </p>
                                                            <p className="text-muted-foreground">
                                                                Uploaded by{' '}
                                                                {
                                                                    photo.uploaded_by
                                                                }
                                                            </p>
                                                            <p className="text-muted-foreground">
                                                                {formatDate(
                                                                    photo.uploaded_at,
                                                                )}
                                                            </p>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        ) : (
                                            <div className="rounded-2xl border border-dashed border-border/70 bg-muted/15 p-4 text-sm text-muted-foreground">
                                                No reference photos uploaded
                                                yet for this stand.
                                            </div>
                                        )}

                                        <Form
                                            {...StandPhotoController.store.form(
                                                currentStand.stand_id,
                                            )}
                                            encType="multipart/form-data"
                                            className="grid gap-4 rounded-2xl border border-border/70 bg-muted/10 p-4"
                                        >
                                            {({ processing, errors }) => (
                                                <>
                                                    <div className="grid gap-2">
                                                        <label className="text-sm font-medium">
                                                            Photos
                                                        </label>
                                                        <input
                                                            type="file"
                                                            name="photos[]"
                                                            accept="image/*"
                                                            multiple
                                                            className="border-input file:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 rounded-md border bg-transparent text-sm file:mr-4 file:border-0 file:bg-transparent file:font-medium focus-visible:ring-[3px]"
                                                        />
                                                        <InputError
                                                            message={
                                                                errors.photos
                                                            }
                                                        />
                                                    </div>
                                                    <div className="grid gap-2">
                                                        <label className="text-sm font-medium">
                                                            Caption
                                                        </label>
                                                        <input
                                                            type="text"
                                                            name="caption"
                                                            className="border-input focus-visible:border-ring focus-visible:ring-ring/50 h-10 rounded-md border bg-transparent px-3 text-sm outline-none focus-visible:ring-[3px]"
                                                            placeholder="Incoming bird over the hedge line"
                                                        />
                                                        <InputError
                                                            message={
                                                                errors.caption
                                                            }
                                                        />
                                                    </div>
                                                    <Button
                                                        disabled={processing}
                                                        className="sm:w-fit"
                                                    >
                                                        Upload stand photo
                                                    </Button>
                                                </>
                                            )}
                                        </Form>
                                    </CardContent>
                                </Card>
                            </>
                        ) : (
                            <Card className="border-border/70">
                                <CardHeader>
                                    <CardTitle>No stand selected yet</CardTitle>
                                    <CardDescription>
                                        Add the first stand from the panel on
                                        the left to start live scoring.
                                    </CardDescription>
                                </CardHeader>
                            </Card>
                        )}
                    </div>
                </div>
            </div>
        </>
    );
}

LiveScoring.layout = {
    breadcrumbs: [
        {
            title: 'Dashboard',
            href: dashboard(),
        },
        {
            title: 'Live scoring',
            href: ScoringSessionController.liveSetup(),
        },
    ],
};
