import { Card, PageHeader, StatCard, StatusBadge } from '@/Components/admin/primitives';
import { Button } from '@/Components/ui/button';
import AdminLayout from '@/Layouts/AdminLayout';
import { Head, Link } from '@inertiajs/react';
import { Gamepad2, MessageSquare, Plus, Star, Users } from 'lucide-react';

type Props = {
    stats: Record<'games' | 'published' | 'drafts' | 'users' | 'new_users' | 'ratings' | 'avg_rating' | 'reviews' | 'pending' | 'hidden', number>;
    activity: { date: string; ratings: number; signups: number }[];
    top: { id: number; title: string; slug: string; wishlist_count: number; rating_avg: number }[];
    recent_reviews: { id: number; body: string; status: string; user: string | null; game: { title: string; slug: string } | null; at: string }[];
};

function ActivityChart({ data }: { data: Props['activity'] }) {
    const max = Math.max(1, ...data.map((d) => Math.max(d.ratings, d.signups)));
    return (
        <div>
            <div className="flex h-36 items-end gap-1.5" role="img" aria-label="Ratings and signups over the last 14 days">
                {data.map((d) => (
                    <div key={d.date} className="group relative flex h-full flex-1 items-end gap-0.5" title={`${d.date}: ${d.ratings} ratings, ${d.signups} signups`}>
                        <div className="flex-1 rounded-t bg-primary/80 transition group-hover:bg-primary" style={{ height: `${(d.ratings / max) * 100}%`, minHeight: d.ratings ? 3 : 1 }} />
                        <div className="flex-1 rounded-t bg-foreground/25 transition group-hover:bg-foreground/40" style={{ height: `${(d.signups / max) * 100}%`, minHeight: d.signups ? 3 : 1 }} />
                    </div>
                ))}
            </div>
            <div className="mt-3 flex items-center justify-between text-caption">
                <span>{data[0]?.date.slice(5)}</span>
                <span className="flex gap-4"><span className="inline-flex items-center gap-1.5"><i className="size-2 rounded-sm bg-primary/80" />Ratings</span><span className="inline-flex items-center gap-1.5"><i className="size-2 rounded-sm bg-foreground/25" />Signups</span></span>
                <span>{data[data.length - 1]?.date.slice(5)}</span>
            </div>
        </div>
    );
}

export default function Dashboard({ stats, activity, top, recent_reviews }: Props) {
    return (
        <AdminLayout>
            <Head title="Admin" />
            <PageHeader title="Dashboard" description="What's happening on Aether." actions={<Link href={route('admin.games.create')}><Button><Plus />New game</Button></Link>} />

            <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
                <StatCard label="Games" value={stats.games} hint={`${stats.published} published · ${stats.drafts} drafts`} icon={Gamepad2} href={route('admin.games.index')} />
                <StatCard label="Users" value={stats.users} hint={`+${stats.new_users} this week`} icon={Users} href={route('admin.users.index')} />
                <StatCard label="Ratings" value={stats.ratings.toLocaleString()} hint={`${stats.avg_rating.toFixed(1)} average`} icon={Star} />
                <StatCard label="Reviews" value={stats.reviews} hint={stats.pending ? `${stats.pending} awaiting moderation` : `${stats.hidden} hidden`} icon={MessageSquare} href={route('admin.reviews.index')} />
            </div>

            <div className="mt-4 grid gap-4 lg:grid-cols-3">
                <Card title="Last 14 days" className="lg:col-span-2"><ActivityChart data={activity} /></Card>
                <Card title="Most wishlisted">
                    <ol className="space-y-3">
                        {top.map((g, i) => (
                            <li key={g.id} className="flex items-center gap-3 text-sm">
                                <span className="w-4 text-center text-muted-foreground tabular-nums">{i + 1}</span>
                                <Link href={route('admin.games.edit', g.slug)} className="min-w-0 flex-1 truncate hover:underline">{g.title}</Link>
                                <span className="text-caption tabular-nums">{g.wishlist_count}</span>
                            </li>
                        ))}
                        {top.length === 0 && <p className="text-sm text-muted-foreground">No data yet.</p>}
                    </ol>
                </Card>
            </div>

            <Card title="Recent reviews" className="mt-4">
                <ul className="divide-y divide-border">
                    {recent_reviews.map((r) => (
                        <li key={r.id} className="flex items-start gap-3 py-3 first:pt-0 last:pb-0">
                            <div className="min-w-0 flex-1">
                                <p className="text-sm"><span className="font-medium">{r.user}</span> <span className="text-muted-foreground">on</span> {r.game ? <Link href={route('games.show', r.game.slug)} className="hover:underline">{r.game.title}</Link> : '—'}</p>
                                <p className="mt-0.5 line-clamp-1 text-sm text-muted-foreground">{r.body}</p>
                            </div>
                            <StatusBadge value={r.status} /><span className="text-caption w-24 text-right">{r.at}</span>
                        </li>
                    ))}
                    {recent_reviews.length === 0 && <p className="text-sm text-muted-foreground">No reviews yet.</p>}
                </ul>
                <div className="mt-4"><Link href={route('admin.reviews.index')} className="text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">Moderate reviews →</Link></div>
            </Card>
        </AdminLayout>
    );
}
