import { Head, Link } from '@inertiajs/react';
import { Activity, ClipboardPenLine, MapPinned, Shield, Users } from 'lucide-react';
import admin from '@/routes/admin';
import ScoringSessionController from '@/actions/App/Http/Controllers/ScoringSessionController';
import Heading from '@/components/heading';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

type AdminDashboardProps = {
    stats: {
        users: number;
        admins: number;
        locations: number;
        stands: number;
        sessions: number;
    };
    recentLocations: Array<{
        id: number;
        name: string;
        town: string;
        region: string;
        stands_count: number;
        is_active: boolean;
    }>;
    memberLeagueTable: Array<{
        id: number;
        rank: number;
        name: string;
        email: string;
        sessions_count: number;
        targets_hit: number;
        targets_attempted: number;
        hit_percentage: number;
        best_score: number | null;
        average_score: number | null;
        best_stand: {
            stand_name: string;
            position_label: string | null;
            targets_hit: number;
            targets_attempted: number;
            hit_percentage: number;
        } | null;
        lowest_stand: {
            stand_name: string;
            position_label: string | null;
            targets_hit: number;
            targets_attempted: number;
            hit_percentage: number;
        } | null;
        last_scored_at: string | null;
    }>;
    recentCompletedScores: Array<{
        session_id: number;
        session_name: string | null;
        shot_at: string | null;
        location_name: string | null;
        user_name: string | null;
        user_email: string | null;
        targets_hit: number;
        targets_attempted: number;
        hit_percentage: number;
    }>;
};

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 formatAverageScore(value: number | null): string {
    if (value === null) {
        return 'No rounds yet';
    }

    return value % 1 === 0 ? value.toFixed(0) : value.toFixed(1);
}

function formatStandSummary(stand: AdminDashboardProps['memberLeagueTable'][number]['best_stand']): string {
    if (!stand) {
        return 'No stand scores yet';
    }

    const label = stand.position_label
        ? `${stand.stand_name} (Pos ${stand.position_label})`
        : stand.stand_name;

    return `${label} · ${stand.targets_hit}/${stand.targets_attempted}`;
}

export default function AdminDashboard({
    stats,
    recentLocations,
    memberLeagueTable,
    recentCompletedScores,
}: AdminDashboardProps) {
    const statCards = [
        {
            title: 'Registered shooters',
            value: stats.users,
            description: 'Members and staff with platform access',
            icon: Users,
        },
        {
            title: 'Admin users',
            value: stats.admins,
            description: 'Users who can manage venues and setup',
            icon: Shield,
        },
        {
            title: 'Course locations',
            value: stats.locations,
            description: 'Grounds available for scoring and setup',
            icon: MapPinned,
        },
        {
            title: 'Configured stands',
            value: stats.stands,
            description: 'Stations with clay presentation details',
            icon: Activity,
        },
        {
            title: 'Scoring sessions',
            value: stats.sessions,
            description: 'Rounds created for squads and player scoring',
            icon: ClipboardPenLine,
        },
    ];

    return (
        <>
            <Head title="Admin dashboard" />

            <div className="space-y-6 p-4 md:p-6">
                <Heading
                    title="Admin dashboard"
                    description="Venue health, member form, and operational shortcuts now live together in a dedicated admin view."
                />

                <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-5">
                    {statCards.map((card) => (
                        <Card key={card.title} className="h-full border-border/70">
                            <CardHeader className="flex flex-col gap-3 space-y-0 sm:flex-row sm:items-start sm:justify-between">
                                <div className="min-w-0 space-y-1">
                                    <CardDescription>{card.title}</CardDescription>
                                    <CardTitle className="break-words text-2xl sm:text-3xl">
                                        {card.value}
                                    </CardTitle>
                                </div>
                                <div className="w-fit rounded-xl bg-primary/10 p-2 text-primary">
                                    <card.icon className="size-5" />
                                </div>
                            </CardHeader>
                            <CardContent>
                                <p className="text-sm text-muted-foreground">
                                    {card.description}
                                </p>
                            </CardContent>
                        </Card>
                    ))}
                </section>

                <section className="grid gap-4 lg:grid-cols-4">
                    <Card className="border-border/70 lg:col-span-3">
                        <CardHeader>
                            <CardTitle>Admin actions</CardTitle>
                            <CardDescription>
                                Jump into the areas most often used for venue and member management.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                            <Link
                                href={admin.users.index()}
                                className="rounded-2xl border border-border/70 bg-muted/20 p-4 transition-colors hover:bg-muted/30"
                            >
                                <Users className="size-5 text-primary" />
                                <p className="mt-3 font-medium text-foreground">Users</p>
                                <p className="mt-1 text-sm text-muted-foreground">
                                    Manage member access and administrator roles.
                                </p>
                            </Link>
                            <Link
                                href={admin.locations.index()}
                                className="rounded-2xl border border-border/70 bg-muted/20 p-4 transition-colors hover:bg-muted/30"
                            >
                                <MapPinned className="size-5 text-primary" />
                                <p className="mt-3 font-medium text-foreground">Locations</p>
                                <p className="mt-1 text-sm text-muted-foreground">
                                    Maintain courses, stands, and clay setup details.
                                </p>
                            </Link>
                            <Link
                                href={admin.audit.index()}
                                className="rounded-2xl border border-border/70 bg-muted/20 p-4 transition-colors hover:bg-muted/30"
                            >
                                <Activity className="size-5 text-primary" />
                                <p className="mt-3 font-medium text-foreground">Audit log</p>
                                <p className="mt-1 text-sm text-muted-foreground">
                                    Review user activity and captured application errors.
                                </p>
                            </Link>
                            <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">Scoring setup</p>
                                <p className="mt-1 text-sm text-muted-foreground">
                                    Start new sessions and review the latest scorecards.
                                </p>
                            </Link>
                        </CardContent>
                    </Card>

                    <Card className="border-border/70">
                        <CardHeader>
                            <CardTitle>Admin summary</CardTitle>
                            <CardDescription>
                                A quick read on club activity 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">
                                Member dashboards now stay personal, while admin reporting and management live here.
                            </div>
                            <div className="rounded-2xl border border-border/70 bg-muted/20 p-4">
                                Use the administration menu for operational tasks without crowding the standard scoring flow.
                            </div>
                            <div className="rounded-2xl border border-border/70 bg-muted/20 p-4">
                                The league table and recent scorecards remain available here for oversight and comparison.
                            </div>
                        </CardContent>
                    </Card>
                </section>

                <section className="grid gap-4 xl:grid-cols-[1.2fr_0.8fr]">
                    <Card className="min-w-0 border-border/70">
                        <CardHeader>
                            <CardTitle>Member league table</CardTitle>
                            <CardDescription>
                                Every member ranked by average score, with round and stand highlights side by side.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            {memberLeagueTable.length > 0 ? (
                                <>
                                    <div className="space-y-3 md:hidden">
                                        {memberLeagueTable.map((member) => (
                                            <div
                                                key={member.id}
                                                className="rounded-2xl border border-border/70 bg-muted/15 p-4"
                                            >
                                                <div className="flex items-start justify-between gap-3">
                                                    <div className="min-w-0">
                                                        <p className="font-medium text-foreground">
                                                            {member.rank}. {member.name}
                                                        </p>
                                                        <p className="break-all text-xs text-muted-foreground">
                                                            {member.email}
                                                        </p>
                                                    </div>
                                                    <Badge variant="secondary">
                                                        {formatPercentage(member.hit_percentage)}
                                                    </Badge>
                                                </div>
                                                <div className="mt-4 grid gap-3 sm:grid-cols-2">
                                                    <div>
                                                        <p className="text-xs uppercase tracking-wide text-muted-foreground">Total</p>
                                                        <p className="font-medium text-foreground">
                                                            {member.targets_hit}/{member.targets_attempted}
                                                        </p>
                                                        <p className="text-xs text-muted-foreground">
                                                            {member.sessions_count} sessions
                                                        </p>
                                                    </div>
                                                    <div>
                                                        <p className="text-xs uppercase tracking-wide text-muted-foreground">Best / Average</p>
                                                        <p className="font-medium text-foreground">
                                                            {member.best_score ?? 'No rounds yet'}
                                                        </p>
                                                        <p className="text-xs text-muted-foreground">
                                                            Avg {formatAverageScore(member.average_score)}
                                                        </p>
                                                    </div>
                                                    <div>
                                                        <p className="text-xs uppercase tracking-wide text-muted-foreground">Best stand</p>
                                                        <p className="text-sm font-medium text-foreground">
                                                            {formatStandSummary(member.best_stand)}
                                                        </p>
                                                    </div>
                                                    <div>
                                                        <p className="text-xs uppercase tracking-wide text-muted-foreground">Lowest stand</p>
                                                        <p className="text-sm font-medium text-foreground">
                                                            {formatStandSummary(member.lowest_stand)}
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>

                                    <div className="hidden overflow-hidden rounded-2xl border border-border/70 md:block">
                                        <div className="overflow-x-auto">
                                            <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">Member</th>
                                                        <th className="px-4 py-3 font-medium">Total</th>
                                                        <th className="px-4 py-3 font-medium">Best score</th>
                                                        <th className="px-4 py-3 font-medium">Average</th>
                                                        <th className="px-4 py-3 font-medium">Best stand</th>
                                                        <th className="px-4 py-3 font-medium">Lowest stand</th>
                                                    </tr>
                                                </thead>
                                                <tbody className="divide-y divide-border/70 bg-background">
                                                    {memberLeagueTable.map((member) => (
                                                        <tr key={member.id} className="align-top">
                                                            <td className="px-4 py-4 font-semibold text-foreground">
                                                                {member.rank}
                                                            </td>
                                                            <td className="px-4 py-4">
                                                                <div className="space-y-1">
                                                                    <p className="font-medium text-foreground">
                                                                        {member.name}
                                                                    </p>
                                                                    <p className="text-muted-foreground">
                                                                        {member.email}
                                                                    </p>
                                                                    <p className="text-xs text-muted-foreground">
                                                                        {member.last_scored_at
                                                                            ? `Last scored ${formatDate(member.last_scored_at)}`
                                                                            : 'No rounds scored yet'}
                                                                    </p>
                                                                </div>
                                                            </td>
                                                            <td className="px-4 py-4">
                                                                <div className="space-y-1">
                                                                    <p className="font-medium text-foreground">
                                                                        {member.targets_hit}/{member.targets_attempted}
                                                                    </p>
                                                                    <p className="text-xs text-muted-foreground">
                                                                        {member.sessions_count} sessions
                                                                    </p>
                                                                    <Badge variant="secondary">
                                                                        {formatPercentage(member.hit_percentage)}
                                                                    </Badge>
                                                                </div>
                                                            </td>
                                                            <td className="px-4 py-4 font-medium text-foreground">
                                                                {member.best_score ?? 'No rounds yet'}
                                                            </td>
                                                            <td className="px-4 py-4 font-medium text-foreground">
                                                                {formatAverageScore(member.average_score)}
                                                            </td>
                                                            <td className="px-4 py-4">
                                                                <div className="space-y-1">
                                                                    <p className="font-medium text-foreground">
                                                                        {formatStandSummary(member.best_stand)}
                                                                    </p>
                                                                    <p className="text-xs text-muted-foreground">
                                                                        {member.best_stand
                                                                            ? formatPercentage(member.best_stand.hit_percentage)
                                                                            : 'No stand scores yet'}
                                                                    </p>
                                                                </div>
                                                            </td>
                                                            <td className="px-4 py-4">
                                                                <div className="space-y-1">
                                                                    <p className="font-medium text-foreground">
                                                                        {formatStandSummary(member.lowest_stand)}
                                                                    </p>
                                                                    <p className="text-xs text-muted-foreground">
                                                                        {member.lowest_stand
                                                                            ? formatPercentage(member.lowest_stand.hit_percentage)
                                                                            : 'No stand scores yet'}
                                                                    </p>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    ))}
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </>
                            ) : (
                                <p className="text-sm text-muted-foreground">
                                    League table data will appear once members start recording rounds.
                                </p>
                            )}
                        </CardContent>
                    </Card>

                    <Card className="min-w-0 border-border/70">
                        <CardHeader>
                            <CardTitle>Recent member scores</CardTitle>
                            <CardDescription>
                                Open completed scorecards from other members and compare round results.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            {recentCompletedScores.length > 0 ? (
                                recentCompletedScores.map((score, index) => (
                                    <Link
                                        key={`${score.session_id}-${score.user_email ?? index}`}
                                        href={ScoringSessionController.show(score.session_id)}
                                        className="block rounded-2xl border border-border/70 bg-muted/20 p-4 transition-colors hover:bg-muted/30"
                                    >
                                        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                                            <div className="min-w-0">
                                                <p className="font-medium">
                                                    {score.user_name ?? 'Unknown member'}
                                                </p>
                                                <p className="text-sm text-muted-foreground">
                                                    {score.session_name ?? 'Completed round'}
                                                    {score.location_name ? ` · ${score.location_name}` : ''}
                                                </p>
                                            </div>
                                            <Badge variant="secondary" className="w-fit">
                                                {formatPercentage(score.hit_percentage)}
                                            </Badge>
                                        </div>
                                        <p className="mt-2 text-sm text-muted-foreground">
                                            {score.targets_hit}/{score.targets_attempted}
                                            {' · '}
                                            {score.shot_at ? formatDate(score.shot_at) : 'No date'}
                                        </p>
                                    </Link>
                                ))
                            ) : (
                                <p className="text-sm text-muted-foreground">
                                    Completed member rounds will appear here once scores are saved.
                                </p>
                            )}
                        </CardContent>
                    </Card>
                </section>

                <section>
                    <Card className="min-w-0 border-border/70">
                        <CardHeader>
                            <CardTitle>Recent course locations</CardTitle>
                            <CardDescription>
                                A quick look at the grounds that already have stands configured.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            {recentLocations.length > 0 ? (
                                recentLocations.map((location) => (
                                    <div
                                        key={location.id}
                                        className="flex flex-col gap-3 rounded-2xl border border-border/70 bg-muted/20 p-4 sm:flex-row sm:items-center sm:justify-between"
                                    >
                                        <div className="min-w-0">
                                            <p className="font-medium">
                                                {location.name}
                                            </p>
                                            <p className="text-sm text-muted-foreground">
                                                {location.town}, {location.region}
                                            </p>
                                        </div>
                                        <div className="flex flex-wrap items-center gap-2">
                                            <Badge variant="secondary">
                                                {location.stands_count} stands
                                            </Badge>
                                            <Badge
                                                className={
                                                    location.is_active
                                                        ? 'bg-emerald-600/10 text-emerald-700 hover:bg-emerald-600/10 dark:text-emerald-300'
                                                        : 'bg-muted text-muted-foreground hover:bg-muted'
                                                }
                                            >
                                                {location.is_active ? 'Active' : 'Offline'}
                                            </Badge>
                                        </div>
                                    </div>
                                ))
                            ) : (
                                <p className="text-sm text-muted-foreground">
                                    No locations are configured yet. Use the admin area to add your first course.
                                </p>
                            )}
                        </CardContent>
                    </Card>
                </section>
            </div>
        </>
    );
}
