import { Head, Link } from '@inertiajs/react';
import ScoringSessionController from '@/actions/App/Http/Controllers/ScoringSessionController';
import Heading from '@/components/heading';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { dashboard } from '@/routes';

type Session = {
    id: number;
    name: string;
    status: string;
    shot_at: string | null;
    location: {
        name: string;
        town: string;
        region: string;
    } | null;
};

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

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

type PlayerResult = {
    rank: number;
    targets_hit: number;
    targets_attempted: number;
    hit_percentage: number;
    user: {
        id: number;
        name: string;
        email: string;
    };
    scores: Record<string, number>;
};

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

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

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

function formatPercentage(value: number): string {
    return `${value.toFixed(2)}%`;
}

function formatDate(value: string | null): string {
    if (!value) {
        return 'No date recorded';
    }

    return new Intl.DateTimeFormat('en-GB', {
        day: 'numeric',
        month: 'short',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    }).format(new Date(value));
}

function scoreForTarget(result: PlayerResult, targetLabel: string): number {
    return result.scores[targetLabel] ?? 0;
}

export default function ScoringStandShow({
    session,
    stand,
    targets,
    currentPlayer,
    otherPlayers,
    standPhotos,
}: {
    session: Session;
    stand: Stand;
    targets: Target[];
    currentPlayer: PlayerResult | null;
    otherPlayers: PlayerResult[];
    standPhotos: StandPhoto[];
}) {
    const locationDescription = session.location
        ? `${session.location.name} · ${session.location.town}, ${session.location.region}`
        : 'Location pending';

    const playerTableRows = currentPlayer
        ? [currentPlayer, ...otherPlayers]
        : otherPlayers;

    return (
        <>
            <Head title={`${stand.stand_name} · ${session.name}`} />

            <div className="space-y-6 p-4 md:p-6">
                <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
                    <Heading
                        title={stand.stand_name}
                        description={`${locationDescription} · ${session.name}`}
                    />
                    <div className="flex flex-wrap gap-2">
                        <Badge variant="secondary">
                            {stand.position_label
                                ? `Position ${stand.position_label}`
                                : 'No position'}
                        </Badge>
                        <Badge variant="secondary">
                            {formatMode(stand.shooting_mode)}
                        </Badge>
                        <Badge variant="secondary">
                            {formatScoringType(stand.scoring_type)}
                        </Badge>
                        <Badge
                            className={
                                session.status === 'completed'
                                    ? 'bg-emerald-600/10 text-emerald-700 hover:bg-emerald-600/10 dark:text-emerald-300'
                                    : 'bg-amber-500/10 text-amber-700 hover:bg-amber-500/10 dark:text-amber-300'
                            }
                        >
                            {session.status === 'completed'
                                ? 'Completed'
                                : 'In progress'}
                        </Badge>
                    </div>
                </div>

                <div className="grid gap-6 xl:grid-cols-[0.72fr_1.28fr]">
                    <div className="space-y-6">
                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Stand overview</CardTitle>
                                <CardDescription>
                                    Review the setup, total shot capacity, and the scorecard date for this stand.
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                <div className="grid gap-4 sm:grid-cols-2">
                                    <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                        <p className="text-sm text-muted-foreground">
                                            Total possible hits
                                        </p>
                                        <p className="mt-1 text-2xl font-semibold">
                                            {stand.total_possible_hits}
                                        </p>
                                    </div>
                                    <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                        <p className="text-sm text-muted-foreground">
                                            Shot at
                                        </p>
                                        <p className="mt-1 text-base font-semibold">
                                            {formatDate(session.shot_at)}
                                        </p>
                                    </div>
                                </div>
                                <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                    <p className="text-sm text-muted-foreground">
                                        Clay layout
                                    </p>
                                    <div className="mt-3 flex flex-wrap gap-2">
                                        {targets.map((target) => (
                                            <Badge
                                                key={target.label}
                                                variant="secondary"
                                                className="gap-1"
                                            >
                                                {target.display_label}: {target.type}
                                            </Badge>
                                        ))}
                                    </div>
                                </div>
                                <Button asChild variant="outline" className="w-full">
                                    <Link href={ScoringSessionController.show(session.id)}>
                                        Back to full scorecard
                                    </Link>
                                </Button>
                            </CardContent>
                        </Card>

                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Your result on this stand</CardTitle>
                                <CardDescription>
                                    Your totals appear separately here so you can compare them quickly against the field.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                {currentPlayer ? (
                                    <div className="space-y-4">
                                        <div className="grid gap-4 sm:grid-cols-3">
                                            <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                                <p className="text-sm text-muted-foreground">
                                                    Rank
                                                </p>
                                                <p className="mt-1 text-2xl font-semibold">
                                                    #{currentPlayer.rank}
                                                </p>
                                            </div>
                                            <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                                <p className="text-sm text-muted-foreground">
                                                    Hits
                                                </p>
                                                <p className="mt-1 text-2xl font-semibold">
                                                    {currentPlayer.targets_hit}/
                                                    {currentPlayer.targets_attempted}
                                                </p>
                                            </div>
                                            <div className="rounded-2xl border border-border/70 bg-muted/15 p-4">
                                                <p className="text-sm text-muted-foreground">
                                                    Hit rate
                                                </p>
                                                <p className="mt-1 text-2xl font-semibold">
                                                    {formatPercentage(
                                                        currentPlayer.hit_percentage,
                                                    )}
                                                </p>
                                            </div>
                                        </div>

                                        <div className="overflow-hidden rounded-2xl border border-border/70">
                                            <table className="min-w-full text-sm">
                                                <thead className="bg-muted/30 text-left">
                                                    <tr>
                                                        <th className="px-4 py-3 font-medium">
                                                            Target
                                                        </th>
                                                        <th className="px-4 py-3 font-medium">
                                                            Type
                                                        </th>
                                                        <th className="px-4 py-3 font-medium">
                                                            Score
                                                        </th>
                                                    </tr>
                                                </thead>
                                                <tbody className="divide-y divide-border/70 bg-background">
                                                    {targets.map((target) => (
                                                        <tr key={target.label}>
                                                            <td className="px-4 py-3 font-medium">
                                                                {target.display_label}
                                                            </td>
                                                            <td className="px-4 py-3 text-muted-foreground">
                                                                {target.type}
                                                            </td>
                                                            <td className="px-4 py-3 font-medium">
                                                                {scoreForTarget(
                                                                    currentPlayer,
                                                                    target.label,
                                                                )}
                                                            </td>
                                                        </tr>
                                                    ))}
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                ) : (
                                    <div className="rounded-2xl border border-dashed border-border/70 bg-muted/15 p-4 text-sm text-muted-foreground">
                                        You were not part of this scorecard, so there is no personal stand result to show here.
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    </div>

                    <div className="space-y-6">
                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>Stand photos</CardTitle>
                                <CardDescription>
                                    Reference images uploaded for this stand stay attached to the original setup.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                {standPhotos.length > 0 ? (
                                    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
                                        {standPhotos.map((photo) => (
                                            <div
                                                key={photo.id}
                                                className="overflow-hidden rounded-2xl border border-border/70 bg-muted/15"
                                            >
                                                <img
                                                    src={photo.url}
                                                    alt={
                                                        photo.caption ??
                                                        `${stand.stand_name} reference`
                                                    }
                                                    className="h-44 w-full object-cover"
                                                />
                                                <div className="space-y-1 p-4 text-sm">
                                                    <p className="font-medium">
                                                        {photo.caption ??
                                                            'Stand reference photo'}
                                                    </p>
                                                    <p className="text-muted-foreground">
                                                        Uploaded by {photo.uploaded_by}
                                                    </p>
                                                    <p className="text-muted-foreground">
                                                        {formatDate(photo.uploaded_at)}
                                                    </p>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                ) : (
                                    <div className="rounded-2xl border border-dashed border-border/70 bg-muted/15 p-4 text-sm text-muted-foreground">
                                        No photos have been uploaded for this stand yet.
                                    </div>
                                )}
                            </CardContent>
                        </Card>

                        <Card className="border-border/70">
                            <CardHeader>
                                <CardTitle>
                                    {currentPlayer
                                        ? 'Other players on this stand'
                                        : 'Players on this stand'}
                                </CardTitle>
                                <CardDescription>
                                    Compare how the rest of the squad handled the same stand and target pattern.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                {playerTableRows.filter((player) =>
                                    currentPlayer
                                        ? player.user.id !== currentPlayer.user.id
                                        : true,
                                ).length > 0 ? (
                                    <div className="overflow-x-auto rounded-2xl border border-border/70">
                                        <table className="min-w-full text-sm">
                                            <thead className="bg-muted/30 text-left">
                                                <tr>
                                                    <th className="px-4 py-3 font-medium">
                                                        Rank
                                                    </th>
                                                    <th className="px-4 py-3 font-medium">
                                                        Player
                                                    </th>
                                                    {targets.map((target) => (
                                                        <th
                                                            key={target.label}
                                                            className="px-4 py-3 font-medium"
                                                        >
                                                            {target.display_label}
                                                        </th>
                                                    ))}
                                                    <th className="px-4 py-3 font-medium">
                                                        Total
                                                    </th>
                                                    <th className="px-4 py-3 font-medium">
                                                        Hit rate
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody className="divide-y divide-border/70 bg-background">
                                                {playerTableRows
                                                    .filter((player) =>
                                                        currentPlayer
                                                            ? player.user.id !==
                                                              currentPlayer.user.id
                                                            : true,
                                                    )
                                                    .map((player) => (
                                                        <tr key={player.user.id}>
                                                            <td className="px-4 py-3 font-semibold">
                                                                #{player.rank}
                                                            </td>
                                                            <td className="px-4 py-3">
                                                                <div className="space-y-1">
                                                                    <p className="font-medium">
                                                                        {player.user.name}
                                                                    </p>
                                                                    <p className="text-xs text-muted-foreground">
                                                                        {player.user.email}
                                                                    </p>
                                                                </div>
                                                            </td>
                                                            {targets.map((target) => (
                                                                <td
                                                                    key={`${player.user.id}-${target.label}`}
                                                                    className="px-4 py-3 font-medium"
                                                                >
                                                                    {scoreForTarget(
                                                                        player,
                                                                        target.label,
                                                                    )}
                                                                </td>
                                                            ))}
                                                            <td className="px-4 py-3 font-medium">
                                                                {player.targets_hit}/
                                                                {player.targets_attempted}
                                                            </td>
                                                            <td className="px-4 py-3 font-medium">
                                                                {formatPercentage(
                                                                    player.hit_percentage,
                                                                )}
                                                            </td>
                                                        </tr>
                                                    ))}
                                            </tbody>
                                        </table>
                                    </div>
                                ) : (
                                    <div className="rounded-2xl border border-dashed border-border/70 bg-muted/15 p-4 text-sm text-muted-foreground">
                                        No other players were recorded on this stand.
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </div>
        </>
    );
}

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