import { Form, Head, Link } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import ScoringSessionController from '@/actions/App/Http/Controllers/ScoringSessionController';
import Heading from '@/components/heading';
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 { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { dashboard } from '@/routes';

type Location = {
    id: number;
    name: string;
    town: string;
    region: string;
    stands: Array<{
        id: number;
        name: string;
        position_label: string | null;
        clays: Array<{
            label: string;
            type: string;
        }>;
    }>;
};

type Player = {
    id: number;
    name: string;
    email: string;
    player_stat?: {
        hit_percentage: string;
        targets_hit: number;
        targets_attempted: number;
    } | null;
};

type RecentSession = {
    id: number;
    name: string;
    status: string;
    entry_mode?: 'bulk' | 'live';
    stands_count: number;
    location: {
        name: string;
    } | null;
    players: Array<{
        user: {
            name: string;
        };
    }>;
};

type DefaultStandSettings = {
    shooting_mode: string;
    scoring_type: string;
    target_count: number;
};

const shootingModes = [
    { value: 'singles', label: 'Singles' },
    { value: 'report_pairs', label: 'Report Pairs' },
    { value: 'true_pairs', label: 'True Pairs' },
];

const scoringTypes = [
    { value: 'per_clay', label: 'Each clay' },
    { value: 'per_stand', label: 'Whole stand total' },
];

export default function ScoringIndex({
    setupMode = 'bulk',
    locations = [],
    players,
    recentSessions,
    defaultStandSettings,
}: {
    setupMode?: 'bulk' | 'live';
    locations?: Location[];
    players: Player[];
    recentSessions: RecentSession[];
    defaultStandSettings: DefaultStandSettings;
}) {
    if (setupMode === 'live') {
        return (
            <LiveSetupPage
                players={players}
                recentSessions={recentSessions}
                defaultStandSettings={defaultStandSettings}
            />
        );
    }

    const [step, setStep] = useState(1);
    const [selectedLocationId, setSelectedLocationId] = useState<number>(
        locations[0]?.id ?? 0,
    );
    const [selectedPlayerIds, setSelectedPlayerIds] = useState<number[]>([]);
    const [selectedStandIds, setSelectedStandIds] = useState<number[]>([]);
    const [defaultMode, setDefaultMode] = useState(
        defaultStandSettings.shooting_mode,
    );
    const [defaultScoringType, setDefaultScoringType] = useState(
        defaultStandSettings.scoring_type,
    );
    const [defaultTargetCount, setDefaultTargetCount] = useState(
        defaultStandSettings.target_count,
    );
    const [standModes, setStandModes] = useState<Record<number, string>>({});
    const [standScoringTypes, setStandScoringTypes] = useState<
        Record<number, string>
    >({});
    const [standTargetCounts, setStandTargetCounts] = useState<
        Record<number, number>
    >({});

    const selectedLocation = useMemo(
        () => locations.find((location) => location.id === selectedLocationId),
        [locations, selectedLocationId],
    );

    const selectedPlayerNames = useMemo(
        () =>
            players
                .filter((player) => selectedPlayerIds.includes(player.id))
                .map((player) => player.name),
        [players, selectedPlayerIds],
    );

    const togglePlayer = (playerId: number) => {
        setSelectedPlayerIds((current) =>
            current.includes(playerId)
                ? current.filter((value) => value !== playerId)
                : [...current, playerId],
        );
    };

    const toggleStand = (standId: number, checked: boolean) => {
        if (checked) {
            setSelectedStandIds((current) => [...current, standId]);
            setStandModes((current) => ({
                ...current,
                [standId]: current[standId] ?? defaultMode,
            }));
            setStandScoringTypes((current) => ({
                ...current,
                [standId]: current[standId] ?? defaultScoringType,
            }));
            setStandTargetCounts((current) => ({
                ...current,
                [standId]: current[standId] ?? defaultTargetCount,
            }));

            return;
        }

        setSelectedStandIds((current) =>
            current.filter((value) => value !== standId),
        );
    };

    const applyDefaultsToSelectedStands = () => {
        setStandModes((current) =>
            selectedStandIds.reduce<Record<number, string>>(
                (updated, standId) => ({
                    ...updated,
                    [standId]: defaultMode,
                }),
                current,
            ),
        );
        setStandScoringTypes((current) =>
            selectedStandIds.reduce<Record<number, string>>(
                (updated, standId) => ({
                    ...updated,
                    [standId]: defaultScoringType,
                }),
                current,
            ),
        );
        setStandTargetCounts((current) =>
            selectedStandIds.reduce<Record<number, number>>(
                (updated, standId) => ({
                    ...updated,
                    [standId]: defaultTargetCount,
                }),
                current,
            ),
        );
    };

    return (
        <>
            <Head title="Scoring" />

            <div className="space-y-6 p-4 md:p-6">
                <Heading
                    title="Scoring"
                    description="Build a bulk round in a few clear steps, start from shared stand defaults, and still leave room for stand-by-stand tweaks."
                />

                <div className="grid gap-6 xl:grid-cols-[1.12fr_0.88fr]">
                    <Card className="border-border/70">
                        <CardHeader>
                            <CardTitle>Bulk scoring setup</CardTitle>
                            <CardDescription>
                                Step through the round basics, pick the squad,
                                then choose only the stands being shot.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <Form
                                {...ScoringSessionController.store.form()}
                                className="space-y-6"
                            >
                                {({ processing, errors }) => (
                                    <>
                                        <div className="grid gap-3 md:grid-cols-3">
                                            {[
                                                'Round basics',
                                                'Players',
                                                'Stands',
                                            ].map((label, index) => {
                                                const stepNumber = index + 1;
                                                const isCurrent = step === stepNumber;
                                                const isComplete = step > stepNumber;

                                                return (
                                                    <button
                                                        key={label}
                                                        type="button"
                                                        onClick={() => setStep(stepNumber)}
                                                        className={`rounded-2xl border p-4 text-left transition-colors ${
                                                            isCurrent
                                                                ? 'border-primary bg-primary/5'
                                                                : isComplete
                                                                  ? 'border-emerald-500/40 bg-emerald-500/5'
                                                                  : 'border-border/70 bg-muted/15'
                                                        }`}
                                                    >
                                                        <p className="text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground">
                                                            Step {stepNumber}
                                                        </p>
                                                        <p className="mt-2 font-medium">
                                                            {label}
                                                        </p>
                                                    </button>
                                                );
                                            })}
                                        </div>

                                        <section
                                            className={
                                                step === 1 ? 'space-y-6' : 'hidden'
                                            }
                                        >
                                            <div className="grid gap-4 lg:grid-cols-[1fr_0.7fr]">
                                                <div className="grid gap-2">
                                                    <Label htmlFor="session-name">
                                                        Session name
                                                    </Label>
                                                    <Input
                                                        id="session-name"
                                                        name="name"
                                                        placeholder="Saturday morning squad"
                                                    />
                                                    <InputError message={errors.name} />
                                                </div>
                                                <div className="grid gap-2">
                                                    <Label htmlFor="shot-at">
                                                        Shot date and time
                                                    </Label>
                                                    <Input
                                                        id="shot-at"
                                                        name="shot_at"
                                                        type="datetime-local"
                                                    />
                                                    <InputError message={errors.shot_at} />
                                                </div>
                                            </div>

                                            <div className="grid gap-2">
                                                <Label htmlFor="location-id">
                                                    Location
                                                </Label>
                                                <select
                                                    id="location-id"
                                                    name="location_id"
                                                    value={selectedLocationId}
                                                    onChange={(event) => {
                                                        const nextLocationId = Number(
                                                            event.target.value,
                                                        );

                                                        setSelectedLocationId(
                                                            nextLocationId,
                                                        );
                                                        setSelectedStandIds([]);
                                                        setStandModes({});
                                                        setStandScoringTypes({});
                                                        setStandTargetCounts({});
                                                    }}
                                                    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]"
                                                >
                                                    {locations.map((location) => (
                                                        <option
                                                            key={location.id}
                                                            value={location.id}
                                                        >
                                                            {location.name} -{' '}
                                                            {location.town},{' '}
                                                            {location.region}
                                                        </option>
                                                    ))}
                                                </select>
                                                <InputError message={errors.location_id} />
                                            </div>

                                            <div className="rounded-3xl border border-border/70 bg-muted/15 p-5">
                                                <div className="mb-4 flex items-start justify-between gap-4">
                                                    <div>
                                                        <h2 className="font-semibold">
                                                            Default stand pattern
                                                        </h2>
                                                        <p className="text-sm text-muted-foreground">
                                                            Most rounds follow the
                                                            same format. Set it once,
                                                            then only change the few
                                                            stands that need a
                                                            different setup.
                                                        </p>
                                                    </div>
                                                    <Badge variant="secondary">
                                                        Applies when a stand is
                                                        selected
                                                    </Badge>
                                                </div>

                                                <div className="grid gap-4 md:grid-cols-3">
                                                    <div className="grid gap-2">
                                                        <Label>
                                                            Default shooting mode
                                                        </Label>
                                                        <select
                                                            value={defaultMode}
                                                            onChange={(event) =>
                                                                setDefaultMode(
                                                                    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]"
                                                        >
                                                            {shootingModes.map(
                                                                (mode) => (
                                                                    <option
                                                                        key={
                                                                            mode.value
                                                                        }
                                                                        value={
                                                                            mode.value
                                                                        }
                                                                    >
                                                                        {
                                                                            mode.label
                                                                        }
                                                                    </option>
                                                                ),
                                                            )}
                                                        </select>
                                                    </div>
                                                    <div className="grid gap-2">
                                                        <Label>
                                                            Default score by
                                                        </Label>
                                                        <select
                                                            value={
                                                                defaultScoringType
                                                            }
                                                            onChange={(event) =>
                                                                setDefaultScoringType(
                                                                    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]"
                                                        >
                                                            {scoringTypes.map(
                                                                (
                                                                    scoringType,
                                                                ) => (
                                                                    <option
                                                                        key={
                                                                            scoringType.value
                                                                        }
                                                                        value={
                                                                            scoringType.value
                                                                        }
                                                                    >
                                                                        {
                                                                            scoringType.label
                                                                        }
                                                                    </option>
                                                                ),
                                                            )}
                                                        </select>
                                                    </div>
                                                    <div className="grid gap-2">
                                                        <Label>
                                                            Default targets per clay
                                                        </Label>
                                                        <Input
                                                            type="number"
                                                            min={1}
                                                            max={30}
                                                            value={defaultTargetCount}
                                                            onChange={(event) =>
                                                                setDefaultTargetCount(
                                                                    Number(
                                                                        event
                                                                            .target
                                                                            .value,
                                                                    ) || 1,
                                                                )
                                                            }
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                        </section>

                                        <section
                                            className={
                                                step === 2 ? 'space-y-4' : 'hidden'
                                            }
                                        >
                                            <div>
                                                <Label>Players</Label>
                                                <p className="text-sm text-muted-foreground">
                                                    Choose the squad for this
                                                    session. You can still add or
                                                    remove players after the round
                                                    has been created.
                                                </p>
                                            </div>
                                            <div className="grid gap-3 sm:grid-cols-2">
                                                {players.map((player) => {
                                                    const isSelected =
                                                        selectedPlayerIds.includes(
                                                            player.id,
                                                        );

                                                    return (
                                                        <label
                                                            key={player.id}
                                                            className={`rounded-2xl border p-4 text-left transition-colors ${
                                                                isSelected
                                                                    ? 'border-primary bg-primary/5'
                                                                    : 'border-border/70 bg-muted/15'
                                                            }`}
                                                        >
                                                            <div className="flex items-start gap-3">
                                                                <input
                                                                    type="checkbox"
                                                                    checked={
                                                                        isSelected
                                                                    }
                                                                    onChange={() =>
                                                                        togglePlayer(
                                                                            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>
                                                                    {player.player_stat ? (
                                                                        <p className="mt-1 text-xs text-muted-foreground">
                                                                            {
                                                                                player
                                                                                    .player_stat
                                                                                    .hit_percentage
                                                                            }
                                                                            % hit rate,
                                                                            {' '}
                                                                            {
                                                                                player
                                                                                    .player_stat
                                                                                    .targets_hit
                                                                            }
                                                                            /
                                                                            {
                                                                                player
                                                                                    .player_stat
                                                                                    .targets_attempted
                                                                            }
                                                                        </p>
                                                                    ) : null}
                                                                </div>
                                                            </div>
                                                        </label>
                                                    );
                                                })}
                                            </div>
                                            <InputError message={errors.player_ids} />
                                        </section>

                                        <section
                                            className={
                                                step === 3 ? 'space-y-4' : 'hidden'
                                            }
                                        >
                                            <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                                                <div>
                                                    <Label>Stands</Label>
                                                    <p className="text-sm text-muted-foreground">
                                                        Start with the shared stand
                                                        defaults, then override any
                                                        individual stand that needs
                                                        a different mode or scoring
                                                        method.
                                                    </p>
                                                </div>
                                                <Button
                                                    type="button"
                                                    variant="secondary"
                                                    onClick={applyDefaultsToSelectedStands}
                                                    disabled={
                                                        selectedStandIds.length === 0
                                                    }
                                                >
                                                    Reapply defaults to selected stands
                                                </Button>
                                            </div>

                                            <div className="grid gap-3">
                                                {selectedLocation?.stands.map(
                                                    (stand) => {
                                                        const isSelected =
                                                            selectedStandIds.includes(
                                                                stand.id,
                                                            );

                                                        return (
                                                            <div
                                                                key={stand.id}
                                                                className="rounded-2xl border border-border/70 bg-background p-4"
                                                            >
                                                                <div className="flex flex-col gap-4 xl:flex-row xl:justify-between">
                                                                    <label className="flex items-start gap-3">
                                                                        <input
                                                                            type="checkbox"
                                                                            checked={
                                                                                isSelected
                                                                            }
                                                                            onChange={(
                                                                                event,
                                                                            ) =>
                                                                                toggleStand(
                                                                                    stand.id,
                                                                                    event
                                                                                        .target
                                                                                        .checked,
                                                                                )
                                                                            }
                                                                            className="mt-1 size-4 rounded border-border text-primary focus:ring-primary"
                                                                        />
                                                                        <div>
                                                                            <p className="font-medium">
                                                                                {stand.name}
                                                                            </p>
                                                                            <p className="text-sm text-muted-foreground">
                                                                                {stand.position_label
                                                                                    ? `Position ${stand.position_label}`
                                                                                    : 'No position label'}
                                                                            </p>
                                                                            <div className="mt-2 flex flex-wrap gap-2">
                                                                                {stand.clays.map(
                                                                                    (
                                                                                        clay,
                                                                                    ) => (
                                                                                        <Badge
                                                                                            key={`${stand.id}-${clay.label}`}
                                                                                            variant="secondary"
                                                                                        >
                                                                                            {clay.label}:{' '}
                                                                                            {clay.type}
                                                                                        </Badge>
                                                                                    ),
                                                                                )}
                                                                            </div>
                                                                        </div>
                                                                    </label>

                                                                    {isSelected ? (
                                                                        <div className="grid gap-3 md:grid-cols-3 xl:min-w-[34rem]">
                                                                            <div className="grid gap-2">
                                                                                <Label>
                                                                                    Shooting mode
                                                                                </Label>
                                                                                <select
                                                                                    value={
                                                                                        standModes[
                                                                                            stand.id
                                                                                        ] ??
                                                                                        defaultMode
                                                                                    }
                                                                                    onChange={(
                                                                                        event,
                                                                                    ) =>
                                                                                        setStandModes(
                                                                                            (
                                                                                                current,
                                                                                            ) => ({
                                                                                                ...current,
                                                                                                [stand.id]:
                                                                                                    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]"
                                                                                >
                                                                                    {shootingModes.map(
                                                                                        (
                                                                                            mode,
                                                                                        ) => (
                                                                                            <option
                                                                                                key={
                                                                                                    mode.value
                                                                                                }
                                                                                                value={
                                                                                                    mode.value
                                                                                                }
                                                                                            >
                                                                                                {
                                                                                                    mode.label
                                                                                                }
                                                                                            </option>
                                                                                        ),
                                                                                    )}
                                                                                </select>
                                                                            </div>
                                                                            <div className="grid gap-2">
                                                                                <Label>
                                                                                    Score by
                                                                                </Label>
                                                                                <select
                                                                                    value={
                                                                                        standScoringTypes[
                                                                                            stand.id
                                                                                        ] ??
                                                                                        defaultScoringType
                                                                                    }
                                                                                    onChange={(
                                                                                        event,
                                                                                    ) =>
                                                                                        setStandScoringTypes(
                                                                                            (
                                                                                                current,
                                                                                            ) => ({
                                                                                                ...current,
                                                                                                [stand.id]:
                                                                                                    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]"
                                                                                >
                                                                                    {scoringTypes.map(
                                                                                        (
                                                                                            scoringType,
                                                                                        ) => (
                                                                                            <option
                                                                                                key={
                                                                                                    scoringType.value
                                                                                                }
                                                                                                value={
                                                                                                    scoringType.value
                                                                                                }
                                                                                            >
                                                                                                {
                                                                                                    scoringType.label
                                                                                                }
                                                                                            </option>
                                                                                        ),
                                                                                    )}
                                                                                </select>
                                                                            </div>
                                                                            <div className="grid gap-2">
                                                                                <Label>
                                                                                    Targets per clay
                                                                                </Label>
                                                                                <Input
                                                                                    type="number"
                                                                                    min={1}
                                                                                    max={30}
                                                                                    value={
                                                                                        standTargetCounts[
                                                                                            stand.id
                                                                                        ] ??
                                                                                        defaultTargetCount
                                                                                    }
                                                                                    onChange={(
                                                                                        event,
                                                                                    ) =>
                                                                                        setStandTargetCounts(
                                                                                            (
                                                                                                current,
                                                                                            ) => ({
                                                                                                ...current,
                                                                                                [stand.id]:
                                                                                                    Number(
                                                                                                        event
                                                                                                            .target
                                                                                                            .value,
                                                                                                    ) ||
                                                                                                    1,
                                                                                            }),
                                                                                        )
                                                                                    }
                                                                                />
                                                                            </div>
                                                                        </div>
                                                                    ) : null}
                                                                </div>
                                                            </div>
                                                        );
                                                    },
                                                )}
                                            </div>
                                            <InputError message={errors.selected_stands} />

                                            <div className="rounded-3xl border border-border/70 bg-muted/15 p-5">
                                                <h3 className="font-semibold">
                                                    Ready to create
                                                </h3>
                                                <div className="mt-3 flex flex-wrap gap-2 text-sm text-muted-foreground">
                                                    <Badge variant="secondary">
                                                        {selectedPlayerIds.length}{' '}
                                                        players
                                                    </Badge>
                                                    <Badge variant="secondary">
                                                        {selectedStandIds.length}{' '}
                                                        stands
                                                    </Badge>
                                                    <Badge variant="secondary">
                                                        Default {defaultMode.replace(
                                                            '_',
                                                            ' ',
                                                        )}
                                                    </Badge>
                                                    <Badge variant="secondary">
                                                        {defaultScoringType ===
                                                        'per_stand'
                                                            ? 'Stand totals'
                                                            : 'Per clay'}
                                                    </Badge>
                                                </div>
                                                {selectedPlayerNames.length > 0 ? (
                                                    <p className="mt-3 text-sm text-muted-foreground">
                                                        Squad: {selectedPlayerNames.join(', ')}
                                                    </p>
                                                ) : null}
                                            </div>
                                        </section>

                                        {selectedPlayerIds.map((playerId) => (
                                            <input
                                                key={playerId}
                                                type="hidden"
                                                name="player_ids[]"
                                                value={playerId}
                                            />
                                        ))}

                                        {selectedStandIds.map((standId, index) => (
                                            <div key={standId}>
                                                <input
                                                    type="hidden"
                                                    name={`selected_stands[${index}][stand_id]`}
                                                    value={standId}
                                                />
                                                <input
                                                    type="hidden"
                                                    name={`selected_stands[${index}][shooting_mode]`}
                                                    value={
                                                        standModes[standId] ??
                                                        defaultMode
                                                    }
                                                />
                                                <input
                                                    type="hidden"
                                                    name={`selected_stands[${index}][scoring_type]`}
                                                    value={
                                                        standScoringTypes[
                                                            standId
                                                        ] ?? defaultScoringType
                                                    }
                                                />
                                                <input
                                                    type="hidden"
                                                    name={`selected_stands[${index}][target_count]`}
                                                    value={
                                                        standTargetCounts[
                                                            standId
                                                        ] ?? defaultTargetCount
                                                    }
                                                />
                                            </div>
                                        ))}

                                        <div className="grid gap-2">
                                            <Label htmlFor="session-notes">
                                                Session notes
                                            </Label>
                                            <textarea
                                                id="session-notes"
                                                name="notes"
                                                className="border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 min-h-24 rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-[3px]"
                                                placeholder="Optional squad notes, weather, or event context."
                                            />
                                            <InputError message={errors.notes} />
                                        </div>

                                        <div className="flex flex-wrap justify-between gap-3">
                                            <div className="flex gap-3">
                                                {step > 1 ? (
                                                    <Button
                                                        type="button"
                                                        variant="secondary"
                                                        onClick={() =>
                                                            setStep((current) =>
                                                                Math.max(
                                                                    1,
                                                                    current - 1,
                                                                ),
                                                            )
                                                        }
                                                    >
                                                        Back
                                                    </Button>
                                                ) : null}
                                                {step < 3 ? (
                                                    <Button
                                                        type="button"
                                                        onClick={() =>
                                                            setStep((current) =>
                                                                Math.min(
                                                                    3,
                                                                    current + 1,
                                                                ),
                                                            )
                                                        }
                                                    >
                                                        Next step
                                                    </Button>
                                                ) : null}
                                            </div>

                                            {step === 3 ? (
                                                <Button disabled={processing}>
                                                    Create bulk session
                                                </Button>
                                            ) : null}
                                        </div>
                                    </>
                                )}
                            </Form>
                        </CardContent>
                    </Card>

                    <div className="space-y-6">
                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Need live scoring?</CardTitle>
                                <CardDescription>
                                    Stand-by-stand entry now has its own setup
                                    flow, with default stand settings ready for
                                    the round.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <Link
                                    href={ScoringSessionController.liveSetup()}
                                    className="inline-flex h-10 items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground shadow-xs"
                                >
                                    Open live scoring setup
                                </Link>
                            </CardContent>
                        </Card>

                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Recent bulk sessions</CardTitle>
                                <CardDescription>
                                    Reopen saved bulk rounds and continue from
                                    the summary table.
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-3">
                                {recentSessions.length > 0 ? (
                                    recentSessions.map((session) => (
                                        <Link
                                            key={session.id}
                                            href={ScoringSessionController.show(
                                                session.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">
                                                        {session.name}
                                                    </p>
                                                    <p className="text-sm text-muted-foreground">
                                                        {session.location?.name ??
                                                            'Location pending'}
                                                    </p>
                                                </div>
                                                <Badge variant="secondary">
                                                    {session.status ===
                                                    'completed'
                                                        ? 'Completed'
                                                        : 'In progress'}
                                                </Badge>
                                            </div>
                                            <p className="mt-2 text-xs text-muted-foreground">
                                                {session.stands_count} stands
                                            </p>
                                            <p className="mt-2 text-sm text-muted-foreground">
                                                {session.players
                                                    .map(
                                                        (player) =>
                                                            player.user.name,
                                                    )
                                                    .join(', ')}
                                            </p>
                                        </Link>
                                    ))
                                ) : (
                                    <p className="text-sm text-muted-foreground">
                                        No bulk sessions yet. Create your first
                                        round from the steps on the left.
                                    </p>
                                )}
                            </CardContent>
                        </Card>

                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Workflow</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-3 text-sm text-muted-foreground">
                                <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                    Set one shared stand pattern first, then let
                                    only the odd stand break away from it.
                                </div>
                                <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                    Bulk sessions can be corrected later, so the
                                    initial setup does not need to be perfect.
                                </div>
                                <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                    Player lists can be updated after creation if
                                    somebody joins late or drops out.
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </div>
        </>
    );
}

function LiveSetupPage({
    players,
    recentSessions,
    defaultStandSettings,
}: {
    players: Player[];
    recentSessions: RecentSession[];
    defaultStandSettings: DefaultStandSettings;
}) {
    const [step, setStep] = useState(1);
    const [selectedPlayerIds, setSelectedPlayerIds] = useState<number[]>([]);
    const [defaultMode, setDefaultMode] = useState(
        defaultStandSettings.shooting_mode,
    );
    const [defaultScoringType, setDefaultScoringType] = useState(
        defaultStandSettings.scoring_type,
    );
    const [defaultTargetCount, setDefaultTargetCount] = useState(
        defaultStandSettings.target_count,
    );

    const selectedPlayerNames = useMemo(
        () =>
            players
                .filter((player) => selectedPlayerIds.includes(player.id))
                .map((player) => player.name),
        [players, selectedPlayerIds],
    );

    const togglePlayer = (playerId: number) => {
        setSelectedPlayerIds((current) =>
            current.includes(playerId)
                ? current.filter((value) => value !== playerId)
                : [...current, playerId],
        );
    };

    return (
        <>
            <Head title="Live Scoring" />

            <div className="space-y-6 p-4 md:p-6">
                <Heading
                    title="Live scoring"
                    description="Start a round with the squad and the stand pattern you expect to repeat, then add stands as you move around the course."
                />

                <div className="grid gap-6 xl:grid-cols-[1.02fr_0.98fr]">
                    <Card className="border-border/70">
                        <CardHeader>
                            <CardTitle>Live round setup</CardTitle>
                            <CardDescription>
                                Keep setup light, but save the defaults you want
                                waiting on every new stand.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <Form
                                {...ScoringSessionController.storeLive.form()}
                                className="space-y-6"
                            >
                                {({ processing, errors }) => (
                                    <>
                                        <div className="grid gap-3 md:grid-cols-3">
                                            {['Round basics', 'Players', 'Review'].map(
                                                (label, index) => {
                                                    const stepNumber =
                                                        index + 1;

                                                    return (
                                                        <button
                                                            key={label}
                                                            type="button"
                                                            onClick={() =>
                                                                setStep(
                                                                    stepNumber,
                                                                )
                                                            }
                                                            className={`rounded-2xl border p-4 text-left transition-colors ${
                                                                step ===
                                                                stepNumber
                                                                    ? 'border-primary bg-primary/5'
                                                                    : step >
                                                                        stepNumber
                                                                      ? 'border-emerald-500/40 bg-emerald-500/5'
                                                                      : 'border-border/70 bg-muted/15'
                                                            }`}
                                                        >
                                                            <p className="text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground">
                                                                Step {stepNumber}
                                                            </p>
                                                            <p className="mt-2 font-medium">
                                                                {label}
                                                            </p>
                                                        </button>
                                                    );
                                                },
                                            )}
                                        </div>

                                        <section
                                            className={
                                                step === 1 ? 'space-y-6' : 'hidden'
                                            }
                                        >
                                            <div className="grid gap-4 lg:grid-cols-[1fr_0.7fr]">
                                                <div className="grid gap-2">
                                                    <Label htmlFor="live-session-name">
                                                        Session name
                                                    </Label>
                                                    <Input
                                                        id="live-session-name"
                                                        name="name"
                                                        placeholder="Club comp live round"
                                                    />
                                                    <InputError
                                                        message={errors.name}
                                                    />
                                                </div>
                                                <div className="grid gap-2">
                                                    <Label htmlFor="live-shot-at">
                                                        Shot date and time
                                                    </Label>
                                                    <Input
                                                        id="live-shot-at"
                                                        name="shot_at"
                                                        type="datetime-local"
                                                    />
                                                    <InputError
                                                        message={errors.shot_at}
                                                    />
                                                </div>
                                            </div>

                                            <div className="rounded-3xl border border-border/70 bg-muted/15 p-5">
                                                <div className="mb-4">
                                                    <h2 className="font-semibold">
                                                        Default stand settings
                                                    </h2>
                                                    <p className="text-sm text-muted-foreground">
                                                        These defaults prefill the
                                                        add-stand form after the
                                                        round is created, so most
                                                        stands can be added with
                                                        minimal tapping.
                                                    </p>
                                                </div>
                                                <div className="grid gap-4 md:grid-cols-3">
                                                    <div className="grid gap-2">
                                                        <Label>
                                                            Default shooting mode
                                                        </Label>
                                                        <select
                                                            name="default_shooting_mode"
                                                            value={defaultMode}
                                                            onChange={(event) =>
                                                                setDefaultMode(
                                                                    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]"
                                                        >
                                                            {shootingModes.map(
                                                                (mode) => (
                                                                    <option
                                                                        key={
                                                                            mode.value
                                                                        }
                                                                        value={
                                                                            mode.value
                                                                        }
                                                                    >
                                                                        {
                                                                            mode.label
                                                                        }
                                                                    </option>
                                                                ),
                                                            )}
                                                        </select>
                                                        <InputError
                                                            message={
                                                                errors.default_shooting_mode
                                                            }
                                                        />
                                                    </div>
                                                    <div className="grid gap-2">
                                                        <Label>
                                                            Default score by
                                                        </Label>
                                                        <select
                                                            name="default_scoring_type"
                                                            value={
                                                                defaultScoringType
                                                            }
                                                            onChange={(event) =>
                                                                setDefaultScoringType(
                                                                    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]"
                                                        >
                                                            {scoringTypes.map(
                                                                (
                                                                    scoringType,
                                                                ) => (
                                                                    <option
                                                                        key={
                                                                            scoringType.value
                                                                        }
                                                                        value={
                                                                            scoringType.value
                                                                        }
                                                                    >
                                                                        {
                                                                            scoringType.label
                                                                        }
                                                                    </option>
                                                                ),
                                                            )}
                                                        </select>
                                                        <InputError
                                                            message={
                                                                errors.default_scoring_type
                                                            }
                                                        />
                                                    </div>
                                                    <div className="grid gap-2">
                                                        <Label>
                                                            Default targets per clay
                                                        </Label>
                                                        <Input
                                                            type="number"
                                                            name="default_target_count"
                                                            min={1}
                                                            max={30}
                                                            value={defaultTargetCount}
                                                            onChange={(event) =>
                                                                setDefaultTargetCount(
                                                                    Number(
                                                                        event
                                                                            .target
                                                                            .value,
                                                                    ) || 1,
                                                                )
                                                            }
                                                        />
                                                        <InputError
                                                            message={
                                                                errors.default_target_count
                                                            }
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                        </section>

                                        <section
                                            className={
                                                step === 2 ? 'space-y-4' : 'hidden'
                                            }
                                        >
                                            <div>
                                                <Label>Players</Label>
                                                <p className="text-sm text-muted-foreground">
                                                    Pick the squad now. You can
                                                    still add a late arrival or
                                                    remove someone after the round
                                                    has started.
                                                </p>
                                            </div>
                                            <div className="grid gap-3 sm:grid-cols-2">
                                                {players.map((player) => {
                                                    const isSelected =
                                                        selectedPlayerIds.includes(
                                                            player.id,
                                                        );

                                                    return (
                                                        <label
                                                            key={player.id}
                                                            className={`rounded-2xl border p-4 text-left transition-colors ${
                                                                isSelected
                                                                    ? 'border-primary bg-primary/5'
                                                                    : 'border-border/70 bg-muted/15'
                                                            }`}
                                                        >
                                                            <div className="flex items-start gap-3">
                                                                <input
                                                                    type="checkbox"
                                                                    checked={
                                                                        isSelected
                                                                    }
                                                                    onChange={() =>
                                                                        togglePlayer(
                                                                            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>
                                                            </div>
                                                        </label>
                                                    );
                                                })}
                                            </div>
                                            <InputError message={errors.player_ids} />
                                        </section>

                                        <section
                                            className={
                                                step === 3 ? 'space-y-4' : 'hidden'
                                            }
                                        >
                                            <div className="rounded-3xl border border-border/70 bg-muted/15 p-5">
                                                <h2 className="font-semibold">
                                                    Round summary
                                                </h2>
                                                <div className="mt-3 flex flex-wrap gap-2 text-sm text-muted-foreground">
                                                    <Badge variant="secondary">
                                                        {selectedPlayerIds.length}{' '}
                                                        players
                                                    </Badge>
                                                    <Badge variant="secondary">
                                                        {defaultMode.replace(
                                                            '_',
                                                            ' ',
                                                        )}
                                                    </Badge>
                                                    <Badge variant="secondary">
                                                        {defaultScoringType ===
                                                        'per_stand'
                                                            ? 'Stand totals'
                                                            : 'Per clay'}
                                                    </Badge>
                                                    <Badge variant="secondary">
                                                        {defaultTargetCount} per clay
                                                    </Badge>
                                                </div>
                                                {selectedPlayerNames.length > 0 ? (
                                                    <p className="mt-3 text-sm text-muted-foreground">
                                                        Squad: {selectedPlayerNames.join(', ')}
                                                    </p>
                                                ) : null}
                                            </div>
                                        </section>

                                        {selectedPlayerIds.map((playerId) => (
                                            <input
                                                key={playerId}
                                                type="hidden"
                                                name="player_ids[]"
                                                value={playerId}
                                            />
                                        ))}

                                        <div className="flex flex-wrap justify-between gap-3">
                                            <div className="flex gap-3">
                                                {step > 1 ? (
                                                    <Button
                                                        type="button"
                                                        variant="secondary"
                                                        onClick={() =>
                                                            setStep((current) =>
                                                                Math.max(
                                                                    1,
                                                                    current - 1,
                                                                ),
                                                            )
                                                        }
                                                    >
                                                        Back
                                                    </Button>
                                                ) : null}
                                                {step < 3 ? (
                                                    <Button
                                                        type="button"
                                                        onClick={() =>
                                                            setStep((current) =>
                                                                Math.min(
                                                                    3,
                                                                    current + 1,
                                                                ),
                                                            )
                                                        }
                                                    >
                                                        Next step
                                                    </Button>
                                                ) : null}
                                            </div>

                                            {step === 3 ? (
                                                <Button disabled={processing}>
                                                    Start live round
                                                </Button>
                                            ) : null}
                                        </div>
                                    </>
                                )}
                            </Form>
                        </CardContent>
                    </Card>

                    <div className="space-y-6">
                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Prefer bulk scoring?</CardTitle>
                                <CardDescription>
                                    If the whole round will be entered after the
                                    shoot, jump to the bulk scoring setup instead.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <Link
                                    href={ScoringSessionController.index()}
                                    className="inline-flex h-10 items-center rounded-md border border-border px-4 text-sm font-medium"
                                >
                                    Open bulk scoring setup
                                </Link>
                            </CardContent>
                        </Card>

                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Recent live rounds</CardTitle>
                                <CardDescription>
                                    Reopen an in-progress round or review a
                                    completed live session.
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-3">
                                {recentSessions.length > 0 ? (
                                    recentSessions.map((session) => (
                                        <Link
                                            key={session.id}
                                            href={
                                                session.status === 'completed'
                                                    ? ScoringSessionController.show(
                                                          session.id,
                                                      )
                                                    : ScoringSessionController.live(
                                                          session.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">
                                                        {session.name}
                                                    </p>
                                                    <p className="text-sm text-muted-foreground">
                                                        {session.location?.name ??
                                                            'Location set when the first stand is added'}
                                                    </p>
                                                </div>
                                                <Badge variant="secondary">
                                                    {session.status ===
                                                    'completed'
                                                        ? 'Completed'
                                                        : 'In progress'}
                                                </Badge>
                                            </div>
                                            <p className="mt-2 text-xs text-muted-foreground">
                                                {session.stands_count} stands
                                            </p>
                                            <p className="mt-2 text-sm text-muted-foreground">
                                                {session.players
                                                    .map(
                                                        (player) =>
                                                            player.user.name,
                                                    )
                                                    .join(', ')}
                                            </p>
                                        </Link>
                                    ))
                                ) : (
                                    <p className="text-sm text-muted-foreground">
                                        No live rounds yet. Start one from the
                                        setup steps on the left.
                                    </p>
                                )}
                            </CardContent>
                        </Card>

                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Why this flow works</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-3 text-sm text-muted-foreground">
                                <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                    The round starts quickly, but the stand form
                                    still knows the pattern you usually shoot.
                                </div>
                                <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                    You only add stands when you reach them, so
                                    live scoring stays practical on the ground.
                                </div>
                                <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                    Session setup can still be edited later if
                                    the squad changes once the day gets going.
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </div>
        </>
    );
}

ScoringIndex.layout = {
    breadcrumbs: [
        {
            title: 'Dashboard',
            href: dashboard(),
        },
        {
            title: 'Scoring',
            href: ScoringSessionController.index(),
        },
    ],
};
