import { Head, Link, router } from '@inertiajs/react';
import { index as standExplorerIndex, show as standExplorerShow } 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';
import { dashboard } from '@/routes';

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

type ExplorerStand = {
    id: number;
    name: string;
    position_label: string | null;
    clays_per_round: number;
    photo_count: number;
    sessions_count: number;
    targets_hit: number;
    targets_attempted: number;
    hit_percentage: number;
    last_scored_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));
}

export default function StandExplorerOverview({
    locations,
    selectedLocationId,
    selectedLocation,
    stands,
}: {
    locations: ExplorerLocation[];
    selectedLocationId: number | null;
    selectedLocation: Omit<ExplorerLocation, 'stands_count'> | null;
    stands: ExplorerStand[];
}) {
    return (
        <>
            <Head title="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.45fr_0.55fr] lg:items-end">
                        <div className="space-y-4">
                            <Badge className="bg-white/10 text-white hover:bg-white/10">
                                Stand explorer
                            </Badge>
                            <Heading
                                title="Pick a location and compare your stand form."
                                description="Use the location filter to bring every stand into one table, then drill into a stand for your trend line, other players, and reference photos."
                            />
                        </div>
                        <div className="rounded-2xl border border-white/10 bg-white/6 p-4 backdrop-blur-sm">
                            <label
                                htmlFor="stand-explorer-location"
                                className="text-sm font-medium text-white/85"
                            >
                                Location
                            </label>
                            <select
                                id="stand-explorer-location"
                                value={selectedLocationId ?? ''}
                                onChange={(event) => {
                                    const value = Number(event.target.value);

                                    router.get(standExplorerIndex({ query: { location: value } }));
                                }}
                                className="border-input mt-3 h-11 w-full rounded-md border bg-white/10 px-3 text-sm text-white outline-none"
                            >
                                {locations.map((location) => (
                                    <option key={location.id} value={location.id} className="text-black">
                                        {location.name} - {location.town}, {location.region}
                                    </option>
                                ))}
                            </select>
                            <p className="mt-3 text-sm text-white/70">
                                {selectedLocation
                                    ? `${selectedLocation.name} · ${selectedLocation.town}, ${selectedLocation.region}`
                                    : 'No active locations are available yet.'}
                            </p>
                        </div>
                    </div>
                </section>

                <Card className="border-border/70">
                    <CardHeader className="gap-4">
                        <div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
                            <div>
                                <CardTitle>Stand table</CardTitle>
                                <CardDescription>
                                    Your completed-round stats are shown per stand so you can spot where your numbers are strongest or drifting.
                                </CardDescription>
                            </div>
                            {selectedLocation ? (
                                <div className="flex flex-wrap gap-2">
                                    <Badge variant="secondary">
                                        {stands.length} stands
                                    </Badge>
                                    <Button asChild variant="outline">
                                        <Link href={dashboard()}>
                                            Back to dashboard
                                        </Link>
                                    </Button>
                                </div>
                            ) : null}
                        </div>
                    </CardHeader>
                    <CardContent>
                        {selectedLocation ? (
                            <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">Position</th>
                                            <th className="px-4 py-3 font-medium">Stand</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">Photos</th>
                                            <th className="px-4 py-3 font-medium">Last scored</th>
                                            <th className="px-4 py-3 font-medium">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-border/70 bg-background">
                                        {stands.map((stand) => (
                                            <tr key={stand.id}>
                                                <td className="px-4 py-4 font-semibold">
                                                    {stand.position_label ?? 'No position'}
                                                </td>
                                                <td className="px-4 py-4">
                                                    <div className="space-y-1">
                                                        <p className="font-medium text-foreground">
                                                            {stand.name}
                                                        </p>
                                                        <p className="text-xs text-muted-foreground">
                                                            {stand.clays_per_round} clay
                                                            {stand.clays_per_round === 1 ? '' : 's'}
                                                        </p>
                                                    </div>
                                                </td>
                                                <td className="px-4 py-4 font-medium">
                                                    {stand.sessions_count}
                                                </td>
                                                <td className="px-4 py-4 font-medium">
                                                    {stand.targets_hit}/{stand.targets_attempted}
                                                </td>
                                                <td className="px-4 py-4 font-medium">
                                                    {formatPercentage(stand.hit_percentage)}
                                                </td>
                                                <td className="px-4 py-4 font-medium">
                                                    {stand.photo_count}
                                                </td>
                                                <td className="px-4 py-4 text-muted-foreground">
                                                    {formatDate(stand.last_scored_at)}
                                                </td>
                                                <td className="px-4 py-4">
                                                    <Button asChild variant="outline">
                                                        <Link
                                                            href={standExplorerShow({
                                                                location: selectedLocation.id,
                                                                stand: stand.id,
                                                            })}
                                                        >
                                                            Open stand
                                                        </Link>
                                                    </Button>
                                                </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">
                                Add an active location with stands to unlock the stand explorer.
                            </div>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}
