import { Head, Link } from '@inertiajs/react';
import { ClipboardPenLine, Radio, TrendingUp } from 'lucide-react';
import ScoringSessionController from '@/actions/App/Http/Controllers/ScoringSessionController';
import StandExplorerDetail from '@/components/stand-explorer-detail';
import StandExplorerOverview from '@/components/stand-explorer-overview';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

type DashboardProps = {
    playerSummary: {
        sessions_count: number;
        completed_sessions_count: number;
        targets_hit: number;
        targets_attempted: number;
        hit_percentage: number;
        last_scored_at: string | null;
    };
    bestStand: {
        stand_name: string;
        position_label: string | null;
        targets_hit: number;
        targets_attempted: number;
        hit_percentage: number;
    } | null;
    bestOverallScore: {
        session_id: number;
        session_name: string;
        location_name: string;
        shot_at: string | null;
        targets_hit: number;
        targets_attempted: number;
        hit_percentage: number;
    } | null;
    bestClayType: {
        type: string;
        targets_hit: number;
        targets_attempted: number;
        hit_percentage: number;
    } | null;
    scoreTrend: Array<{
        id: number;
        session_name: string;
        shot_at: string | null;
        targets_hit: number;
        targets_attempted: number;
        hit_percentage: number;
    }>;
    standExplorer?: {
        locations: Array<{
            id: number;
            name: string;
            town: string;
            region: string;
            stands_count: number;
        }>;
        selectedLocationId: number | null;
        selectedLocation: {
            id: number;
            name: string;
            town: string;
            region: string;
        } | null;
        stands: Array<{
            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;
        }>;
    } | null;
    standExplorerDetail?: {
        location: {
            id: number;
            name: string;
            town: string;
            region: string;
            stands_count: number;
        };
        stand: {
            id: number;
            name: string;
            position_label: string | null;
            notes: string | null;
            clays_per_round: number;
            photo_count: number;
            clays: Array<{
                id: number;
                label: string;
                type: string;
                notes: string | null;
            }>;
        };
        currentPlayer: {
            sessions_count: number;
            targets_hit: number;
            targets_attempted: number;
            hit_percentage: number;
            last_scored_at: string | null;
        };
        trend: Array<{
            session_id: number;
            session_name: string;
            shot_at: string | null;
            targets_hit: number;
            targets_attempted: number;
            hit_percentage: number;
        }>;
        otherPlayers: Array<{
            rank: number;
            name: string;
            email: string;
            sessions_count: number;
            targets_hit: number;
            targets_attempted: number;
            hit_percentage: number;
            last_scored_at: string | null;
        }>;
        standPhotos: Array<{
            id: number;
            url: string;
            caption: string | null;
            uploaded_by: string;
            uploaded_at: string | null;
        }>;
    } | null;
};

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

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

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

function formatShortDate(value: string | null): string {
    if (!value) {
        return '';
    }

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

function ScoreTrendChart({
    data,
}: {
    data: DashboardProps['scoreTrend'];
}) {
    if (data.length === 0) {
        return (
            <div className="flex min-h-56 items-center justify-center rounded-2xl border border-dashed border-border/70 bg-muted/20 p-6 text-sm text-muted-foreground">
                Complete a few scored rounds to unlock your performance trend.
            </div>
        );
    }

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

    const points = data
        .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="Score 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"
                    />
                    {data.map((point, index) => {
                        const x = padding + index * step;
                        const y = height - padding - (point.hit_percentage / maxValue) * (height - padding * 2);

                        return (
                            <g key={point.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]"
                                >
                                    {formatShortDate(point.shot_at)}
                                </text>
                            </g>
                        );
                    })}
                </svg>
            </div>

            <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                {data.map((point) => (
                    <div
                        key={point.id}
                        className="rounded-2xl border border-border/70 bg-muted/15 p-3 sm:p-4"
                    >
                        <p className="line-clamp-2 text-sm font-medium sm:text-base">{point.session_name}</p>
                        <p className="mt-1 text-sm text-muted-foreground">
                            {formatDate(point.shot_at)}
                        </p>
                        <p className="mt-3 text-base font-semibold sm:text-lg">
                            {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 Dashboard({
    playerSummary,
    bestStand,
    bestOverallScore,
    bestClayType,
    scoreTrend,
    standExplorer,
    standExplorerDetail,
}: DashboardProps) {
    if (standExplorerDetail) {
        return (
            <StandExplorerDetail
                location={standExplorerDetail.location}
                stand={standExplorerDetail.stand}
                currentPlayer={standExplorerDetail.currentPlayer}
                trend={standExplorerDetail.trend}
                otherPlayers={standExplorerDetail.otherPlayers}
                standPhotos={standExplorerDetail.standPhotos}
            />
        );
    }

    if (standExplorer) {
        return (
            <StandExplorerOverview
                locations={standExplorer.locations}
                selectedLocationId={standExplorer.selectedLocationId}
                selectedLocation={standExplorer.selectedLocation}
                stands={standExplorer.stands}
            />
        );
    }

    const playerCards = [
        {
            title: 'Sessions logged',
            value: playerSummary.sessions_count,
            description: `${playerSummary.completed_sessions_count} completed rounds`,
        },
        {
            title: 'Targets hit',
            value: `${playerSummary.targets_hit}/${playerSummary.targets_attempted}`,
            description: `Overall strike rate ${formatPercentage(playerSummary.hit_percentage)}`,
        },
        {
            title: 'Best stand',
            value: bestStand?.position_label
                ? `Stand ${bestStand.position_label}`
                : bestStand?.stand_name ?? 'No data yet',
            description: bestStand
                ? `${bestStand.targets_hit}/${bestStand.targets_attempted} · ${formatPercentage(bestStand.hit_percentage)}`
                : 'Your strongest stand will appear here',
        },
        {
            title: 'Best clay type',
            value: bestClayType?.type ?? 'No data yet',
            description: bestClayType
                ? `${bestClayType.targets_hit}/${bestClayType.targets_attempted} · ${formatPercentage(bestClayType.hit_percentage)}`
                : 'Clay strengths appear after scoring rounds',
        },
    ];

    return (
        <>
            <Head title="My dashboard" />
            <div className="flex flex-1 flex-col gap-4 p-3 sm:gap-6 sm:p-4 md:p-6">
                <section className="overflow-hidden rounded-3xl border border-border/70 bg-[radial-gradient(circle_at_top_left,_rgba(192,139,54,0.2),_transparent_38%),linear-gradient(135deg,_rgba(37,52,47,0.98),_rgba(17,24,22,0.94))] px-4 py-5 text-white shadow-sm sm:px-5 sm:py-6 md:px-8 md:py-8">
                    <div className="grid gap-6 lg:grid-cols-[1.6fr_1fr] lg:items-end">
                        <div className="space-y-4">
                            <Badge className="bg-white/10 text-white hover:bg-white/10">
                                Member dashboard
                            </Badge>
                            <div className="space-y-2">
                                <h1 className="max-w-2xl text-2xl font-semibold tracking-tight sm:text-3xl md:text-4xl">
                                    Keep your scoring form, strongest stands, and recent rounds in one place.
                                </h1>
                                <p className="max-w-2xl text-sm leading-6 text-white/75 md:text-base">
                                    This view is focused on your own performance, so you can review form quickly and jump straight into the next round.
                                </p>
                            </div>
                            <div className="flex flex-col gap-3 sm:flex-row">
                                <Button asChild className="w-full sm:w-auto">
                                    <Link href={ScoringSessionController.index()}>
                                        <ClipboardPenLine className="mr-2 size-4" />
                                        Start scoring
                                    </Link>
                                </Button>
                                <Button asChild variant="secondary" className="w-full sm:w-auto">
                                    <Link href={ScoringSessionController.liveSetup()}>
                                        <Radio className="mr-2 size-4" />
                                        Open live scoring
                                    </Link>
                                </Button>
                            </div>
                        </div>
                        <div className="rounded-2xl border border-white/10 bg-white/6 p-4 backdrop-blur-sm">
                            <p className="text-sm font-medium text-white/85">
                                Personal form
                            </p>
                            <p className="mt-3 break-words text-2xl font-semibold sm:text-3xl">
                                {formatPercentage(playerSummary.hit_percentage)}
                            </p>
                            <p className="mt-1 text-sm text-white/70">
                                {playerSummary.last_scored_at
                                    ? `Last scored ${formatDate(playerSummary.last_scored_at)}`
                                    : 'Your latest score will appear here once a round is saved.'}
                            </p>
                        </div>
                    </div>
                </section>

                <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                    {playerCards.map((card) => (
                        <Card key={card.title} className="h-full border-border/70">
                            <CardHeader className="space-y-1">
                                <CardDescription>{card.title}</CardDescription>
                                <CardTitle className="break-words text-xl leading-tight sm:text-2xl">
                                    {card.value}
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <p className="text-sm text-muted-foreground">
                                    {card.description}
                                </p>
                            </CardContent>
                        </Card>
                    ))}
                </section>

                <section className="grid gap-4 xl:grid-cols-[1.3fr_0.7fr]">
                    <Card className="min-w-0 border-border/70">
                        <CardHeader>
                            <CardTitle>Score trend over time</CardTitle>
                            <CardDescription>
                                Recent rounds plotted by hit percentage so you can spot form changes quickly.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <ScoreTrendChart data={scoreTrend} />
                        </CardContent>
                    </Card>

                    <Card className="min-w-0 border-border/70">
                        <CardHeader>
                            <CardTitle>Personal highlights</CardTitle>
                            <CardDescription>
                                Fast reads on where you are performing best right now.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4 text-sm text-muted-foreground">
                            <div className="rounded-2xl border border-border/70 bg-muted/20 p-4">
                                <p className="font-medium text-foreground">
                                    Best overall score
                                </p>
                                {bestOverallScore ? (
                                    <>
                                        <p className="mt-2 break-words text-xl font-semibold text-foreground sm:text-2xl">
                                            {bestOverallScore.targets_hit}/{bestOverallScore.targets_attempted}
                                        </p>
                                        <p className="mt-1">
                                            {bestOverallScore.session_name} at {bestOverallScore.location_name}
                                        </p>
                                        <p className="mt-1">
                                            {formatPercentage(bestOverallScore.hit_percentage)} on {formatDate(bestOverallScore.shot_at)}
                                        </p>
                                    </>
                                ) : (
                                    <p className="mt-2">
                                        Your top round will appear here once you have scored a session.
                                    </p>
                                )}
                            </div>
                            <div className="rounded-2xl border border-border/70 bg-muted/20 p-4">
                                <p className="font-medium text-foreground">
                                    Best stand
                                </p>
                                {bestStand ? (
                                    <>
                                        <p className="mt-2 break-words text-lg font-semibold text-foreground">
                                            {bestStand.stand_name}
                                        </p>
                                        <p className="mt-1">
                                            {bestStand.position_label
                                                ? `Position ${bestStand.position_label}`
                                                : 'No position set'}
                                        </p>
                                        <p className="mt-1">
                                            {bestStand.targets_hit}/{bestStand.targets_attempted} · {formatPercentage(bestStand.hit_percentage)}
                                        </p>
                                    </>
                                ) : (
                                    <p className="mt-2">
                                        Stand performance appears after your first scored round.
                                    </p>
                                )}
                            </div>
                            <div className="rounded-2xl border border-border/70 bg-muted/20 p-4">
                                <p className="font-medium text-foreground">
                                    Strongest clay type
                                </p>
                                {bestClayType ? (
                                    <>
                                        <p className="mt-2 break-words text-lg font-semibold text-foreground">
                                            {bestClayType.type}
                                        </p>
                                        <p className="mt-1">
                                            {bestClayType.targets_hit}/{bestClayType.targets_attempted} · {formatPercentage(bestClayType.hit_percentage)}
                                        </p>
                                    </>
                                ) : (
                                    <p className="mt-2">
                                        Clay type strengths will show up once enough scores are saved.
                                    </p>
                                )}
                            </div>
                        </CardContent>
                    </Card>
                </section>

                <section className="grid gap-4 lg:grid-cols-2">
                    <Card className="border-border/70">
                        <CardHeader>
                            <CardTitle>Next scoring actions</CardTitle>
                            <CardDescription>
                                Jump straight back into whichever scoring flow you need next.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="grid gap-3 sm:grid-cols-2">
                            <Link
                                href={ScoringSessionController.index()}
                                className="rounded-2xl border border-border/70 bg-muted/20 p-4 transition-colors hover:bg-muted/30"
                            >
                                <ClipboardPenLine className="size-5 text-primary" />
                                <p className="mt-3 font-medium text-foreground">Bulk scoring</p>
                                <p className="mt-1 text-sm text-muted-foreground">
                                    Create a standard scored round and capture everyone’s totals.
                                </p>
                            </Link>
                            <Link
                                href={ScoringSessionController.liveSetup()}
                                className="rounded-2xl border border-border/70 bg-muted/20 p-4 transition-colors hover:bg-muted/30"
                            >
                                <Radio className="size-5 text-primary" />
                                <p className="mt-3 font-medium text-foreground">Live scoring</p>
                                <p className="mt-1 text-sm text-muted-foreground">
                                    Run a live session and keep the squad moving stand by stand.
                                </p>
                            </Link>
                        </CardContent>
                    </Card>

                    <Card className="border-border/70">
                        <CardHeader>
                            <CardTitle>What this dashboard tracks</CardTitle>
                            <CardDescription>
                                Member views now stay focused on your own rounds and progression.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4 text-sm text-muted-foreground">
                            <div className="rounded-2xl border border-border/70 bg-muted/20 p-4">
                                Personal strike rate, recent round trend, and strongest stands stay front and center.
                            </div>
                            <div className="rounded-2xl border border-border/70 bg-muted/20 p-4">
                                Admin reporting and management tools now live on their own dashboard and navigation section.
                            </div>
                            <div className="rounded-2xl border border-border/70 bg-muted/20 p-4">
                                This keeps the member experience simpler while still giving staff a full operational view elsewhere.
                            </div>
                        </CardContent>
                    </Card>
                </section>
            </div>
        </>
    );
}
