import { Head, Link } from '@inertiajs/react';
import { index as standExplorerIndex } from '@/actions/App/Http/Controllers/StandExplorerController';
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';

type Location = {
    id: number;
    name: string;
    town: string;
    region: string;
    stands_count: number;
};

type Clay = {
    id: number;
    label: string;
    type: string;
    notes: string | null;
};

type Stand = {
    id: number;
    name: string;
    position_label: string | null;
    notes: string | null;
    clays_per_round: number;
    photo_count: number;
    clays: Clay[];
};

type CurrentPlayer = {
    sessions_count: number;
    targets_hit: number;
    targets_attempted: number;
    hit_percentage: number;
    last_scored_at: string | null;
};

type TrendPoint = {
    session_id: number;
    session_name: string;
    shot_at: string | null;
    targets_hit: number;
    targets_attempted: number;
    hit_percentage: number;
};

type OtherPlayer = {
    rank: number;
    name: string;
    email: string;
    sessions_count: number;
    targets_hit: number;
    targets_attempted: number;
    hit_percentage: number;
    last_scored_at: string | null;
};

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

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

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

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

function TrendChart({
    trend,
}: {
    trend: TrendPoint[];
}) {
    if (trend.length === 0) {
        return (
            <div className="rounded-2xl border border-dashed border-border/70 bg-muted/15 p-4 text-sm text-muted-foreground">
                You do not have any completed rounds on this stand yet.
            </div>
        );
    }

    const width = 720;
    const height = 220;
    const padding = 20;
    const maxValue = Math.max(...trend.map((point) => point.hit_percentage), 1);
    const step = trend.length > 1 ? (width - padding * 2) / (trend.length - 1) : 0;

    const points = trend
        .map((point, index) => {
            const x = padding + index * step;
            const y = height - padding - (point.hit_percentage / maxValue) * (height - padding * 2);

            return `${x},${y}`;
        })
        .join(' ');

    return (
        <div className="space-y-4">
            <div className="overflow-hidden rounded-2xl border border-border/70 bg-muted/15 p-3 sm:p-4">
                <svg
                    viewBox={`0 0 ${width} ${height}`}
                    className="h-48 w-full sm:h-56"
                    role="img"
                    aria-label="Stand trend over time"
                    preserveAspectRatio="none"
                >
                    {[0, 1, 2, 3].map((index) => {
                        const y = padding + ((height - padding * 2) / 3) * index;

                        return (
                            <line
                                key={index}
                                x1={padding}
                                y1={y}
                                x2={width - padding}
                                y2={y}
                                stroke="currentColor"
                                className="text-border/70"
                                strokeDasharray="4 4"
                            />
                        );
                    })}
                    <polyline
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="4"
                        points={points}
                        className="text-primary"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                    />
                    {trend.map((point, index) => {
                        const x = padding + index * step;
                        const y = height - padding - (point.hit_percentage / maxValue) * (height - padding * 2);

                        return (
                            <g key={point.session_id}>
                                <circle
                                    cx={x}
                                    cy={y}
                                    r="5"
                                    fill="currentColor"
                                    className="text-primary"
                                />
                                <text
                                    x={x}
                                    y={height - 2}
                                    textAnchor="middle"
                                    className="fill-muted-foreground text-[11px]"
                                >
                                    {formatDate(point.shot_at)}
                                </text>
                            </g>
                        );
                    })}
                </svg>
            </div>

            <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                {trend.map((point) => (
                    <div
                        key={point.session_id}
                        className="rounded-2xl border border-border/70 bg-muted/15 p-4"
                    >
                        <p className="font-medium text-foreground">
                            {point.session_name}
                        </p>
                        <p className="mt-1 text-sm text-muted-foreground">
                            {formatDate(point.shot_at)}
                        </p>
                        <p className="mt-3 text-lg font-semibold text-foreground">
                            {point.targets_hit}/{point.targets_attempted}
                        </p>
                        <p className="text-sm text-muted-foreground">
                            {formatPercentage(point.hit_percentage)}
                        </p>
                    </div>
                ))}
            </div>
        </div>
    );
}

export default function StandExplorerDetail({
    location,
    stand,
    currentPlayer,
    trend,
    otherPlayers,
    standPhotos,
}: {
    location: Location;
    stand: Stand;
    currentPlayer: CurrentPlayer;
    trend: TrendPoint[];
    otherPlayers: OtherPlayer[];
    standPhotos: StandPhoto[];
}) {
    return (
        <>
            <Head title={`${stand.name} · Stand explorer`} />

            <div className="flex flex-1 flex-col gap-6 p-4 md:p-6">
                <section className="overflow-hidden rounded-3xl border border-border/70 bg-[radial-gradient(circle_at_top_left,_rgba(121,167,145,0.22),_transparent_36%),linear-gradient(135deg,_rgba(19,33,45,0.98),_rgba(10,18,27,0.94))] px-5 py-6 text-white shadow-sm md:px-8 md:py-8">
                    <div className="grid gap-6 lg:grid-cols-[1.35fr_0.65fr] lg:items-end">
                        <div className="space-y-4">
                            <Badge className="bg-white/10 text-white hover:bg-white/10">
                                Stand detail
                            </Badge>
                            <Heading
                                title={stand.name}
                                description={`${location.name} · ${location.town}, ${location.region}`}
                            />
                            <div className="flex flex-wrap gap-2">
                                <Badge className="bg-white/10 text-white hover:bg-white/10">
                                    {stand.position_label
                                        ? `Position ${stand.position_label}`
                                        : 'No position'}
                                </Badge>
                                <Badge className="bg-white/10 text-white hover:bg-white/10">
                                    {stand.clays_per_round} clay
                                    {stand.clays_per_round === 1 ? '' : 's'}
                                </Badge>
                                <Badge className="bg-white/10 text-white hover:bg-white/10">
                                    {stand.photo_count} photos
                                </Badge>
                            </div>
                        </div>
                        <div className="flex flex-col gap-3 sm:flex-row lg:justify-end">
                            <Button asChild variant="secondary">
                                <Link href={standExplorerIndex({ query: { location: location.id } })}>
                                    Back to stand table
                                </Link>
                            </Button>
                        </div>
                    </div>
                </section>

                <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                    <Card className="border-border/70">
                        <CardHeader className="space-y-1">
                            <CardDescription>Your rounds here</CardDescription>
                            <CardTitle className="text-2xl">
                                {currentPlayer.sessions_count}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card className="border-border/70">
                        <CardHeader className="space-y-1">
                            <CardDescription>Total hits</CardDescription>
                            <CardTitle className="text-2xl">
                                {currentPlayer.targets_hit}/{currentPlayer.targets_attempted}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card className="border-border/70">
                        <CardHeader className="space-y-1">
                            <CardDescription>Hit rate</CardDescription>
                            <CardTitle className="text-2xl">
                                {formatPercentage(currentPlayer.hit_percentage)}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card className="border-border/70">
                        <CardHeader className="space-y-1">
                            <CardDescription>Last scored here</CardDescription>
                            <CardTitle className="text-xl">
                                {formatDate(currentPlayer.last_scored_at)}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                </section>

                <section className="grid gap-4 xl:grid-cols-[1.15fr_0.85fr]">
                    <Card className="border-border/70">
                        <CardHeader>
                            <CardTitle>Your trend on this stand</CardTitle>
                            <CardDescription>
                                Track how your performance on this exact stand has changed across completed rounds.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <TrendChart trend={trend} />
                        </CardContent>
                    </Card>

                    <Card className="border-border/70">
                        <CardHeader>
                            <CardTitle>Stand setup</CardTitle>
                            <CardDescription>
                                Clay layout and notes tied to this stand record.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="flex flex-wrap gap-2">
                                {stand.clays.map((clay) => (
                                    <Badge key={clay.id} variant="secondary" className="gap-1">
                                        {clay.label}: {clay.type}
                                    </Badge>
                                ))}
                            </div>
                            <div className="rounded-2xl border border-border/70 bg-muted/15 p-4 text-sm text-muted-foreground">
                                {stand.notes ?? 'No stand notes have been added yet.'}
                            </div>
                        </CardContent>
                    </Card>
                </section>

                <section className="grid gap-4 xl:grid-cols-[1.05fr_0.95fr]">
                    <Card className="border-border/70">
                        <CardHeader>
                            <CardTitle>Other players on this stand</CardTitle>
                            <CardDescription>
                                Compare your aggregated stand numbers against the rest of the club.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            {otherPlayers.length > 0 ? (
                                <div className="overflow-x-auto rounded-2xl border border-border/70">
                                    <table className="min-w-full divide-y divide-border/70 text-sm">
                                        <thead className="bg-muted/30 text-left">
                                            <tr className="text-muted-foreground">
                                                <th className="px-4 py-3 font-medium">Rank</th>
                                                <th className="px-4 py-3 font-medium">Player</th>
                                                <th className="px-4 py-3 font-medium">Rounds</th>
                                                <th className="px-4 py-3 font-medium">Hits</th>
                                                <th className="px-4 py-3 font-medium">Hit rate</th>
                                                <th className="px-4 py-3 font-medium">Last scored</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-border/70 bg-background">
                                            {otherPlayers.map((player) => (
                                                <tr key={player.email}>
                                                    <td className="px-4 py-4 font-semibold">
                                                        #{player.rank}
                                                    </td>
                                                    <td className="px-4 py-4">
                                                        <div className="space-y-1">
                                                            <p className="font-medium text-foreground">
                                                                {player.name}
                                                            </p>
                                                            <p className="text-xs text-muted-foreground">
                                                                {player.email}
                                                            </p>
                                                        </div>
                                                    </td>
                                                    <td className="px-4 py-4 font-medium">
                                                        {player.sessions_count}
                                                    </td>
                                                    <td className="px-4 py-4 font-medium">
                                                        {player.targets_hit}/{player.targets_attempted}
                                                    </td>
                                                    <td className="px-4 py-4 font-medium">
                                                        {formatPercentage(player.hit_percentage)}
                                                    </td>
                                                    <td className="px-4 py-4 text-muted-foreground">
                                                        {formatDate(player.last_scored_at)}
                                                    </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 have completed rounds on this stand yet.
                                </div>
                            )}
                        </CardContent>
                    </Card>

                    <Card className="border-border/70">
                        <CardHeader>
                            <CardTitle>Stand photos</CardTitle>
                            <CardDescription>
                                Reference images uploaded for this stand remain available here for review.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            {standPhotos.length > 0 ? (
                                <div className="grid gap-4 sm:grid-cols-2">
                                    {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.name} reference`}
                                                className="h-40 w-full object-cover"
                                            />
                                            <div className="space-y-1 p-4 text-sm">
                                                <p className="font-medium text-foreground">
                                                    {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>
                </section>
            </div>
        </>
    );
}
