import { Link } from '@inertiajs/react';
import {
    Activity,
    CheckCircle2,
    Clock,
    FileText,
    Gamepad2,
    MessageSquare,
    Star,
    Trophy,
    Zap,
} from 'lucide-react';

import { AuthorTrendLineChart } from '@/components/dashboard/charts/AuthorTrendLineChart';
import { SubmissionStatusPieChart } from '@/components/dashboard/charts/SubmissionStatusPieChart';
import { DashboardPageHeader } from '@/components/dashboard/DashboardPageHeader';
import { RefreshButton } from '@/components/dashboard/RefreshButton';
import { StatsCard } from '@/components/dashboard/StatsCard';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useTranslation } from '@/contexts/LanguageContext';
import { formatNumber } from '@/lib/format';
import { timeAgo } from '@/lib/time';
import { cn } from '@/lib/utils';

type Trend = 'up' | 'down' | 'neutral';
interface Change { value: number; trend: Trend }

interface SubmissionRow {
    id: number;
    title: string;
    slug: string;
    submission_status: 'draft' | 'pending' | 'approved' | 'rejected';
    submitted_at: string | null;
    reviewed_at: string | null;
    rejection_reason: string | null;
}

interface TopGame {
    id: number;
    title: string;
    slug: string;
    plays_count: number;
}

interface RecentComment {
    id: number;
    comment: string;
    created_at: string;
    username: string;
    game_title: string;
    game_slug: string;
}

export interface AuthorOverviewProps {
    stats: {
        total_submissions: number;
        pending: number;
        approved: number;
        total_plays: number;
        total_comments: number;
        total_ratings: number;
        avg_rating: number;
        author_exp: number;
    };
    changes: {
        plays: Change;
        comments: Change;
    };
    submissions: {
        total: number;
        draft: number;
        pending: number;
        approved: number;
        rejected: number;
    };
    trends: { date: string; plays: number; comments: number }[];
    top_games: TopGame[];
    recent: SubmissionRow[];
    recent_comments: RecentComment[];
}

const STATUS_BADGE: Record<SubmissionRow['submission_status'], { label: string; className: string }> = {
    draft:    { label: 'Draft',    className: 'bg-muted text-muted-foreground' },
    pending:  { label: 'Pending',  className: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300' },
    approved: { label: 'Approved', className: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300' },
    rejected: { label: 'Rejected', className: 'bg-rose-100 text-rose-800 dark:bg-rose-900/40 dark:text-rose-300' },
};

export default function AuthorOverview({
    stats,
    changes,
    submissions,
    trends,
    top_games,
    recent,
    recent_comments,
}: AuthorOverviewProps) {
    const { t } = useTranslation();
    return (
        <>
            <DashboardPageHeader
                title={t('Overview')}
                subtitle={t('Ship new games, follow them through review, and watch the plays, comments, and ratings roll in.')}
                action={<RefreshButton only={['author']} />}
            />

            {/* Stats grid */}
            <div className="mb-6 grid grid-cols-2 gap-4 md:grid-cols-4">
                <StatsCard title={t('Submissions')} value={formatNumber(stats.total_submissions)} icon={Gamepad2} />
                <StatsCard title={t('Pending review')} value={formatNumber(stats.pending)} icon={Clock} />
                <StatsCard title={t('Approved')} value={formatNumber(stats.approved)} icon={CheckCircle2} />
                <StatsCard title={t('Author EXP')} value={formatNumber(stats.author_exp)} icon={Zap} />
                <StatsCard title={t('Total plays')} value={formatNumber(stats.total_plays)} change={changes.plays} icon={Activity} />
                <StatsCard title={t('Comments received')} value={formatNumber(stats.total_comments)} change={changes.comments} icon={MessageSquare} />
                <StatsCard title={t('Ratings received')} value={formatNumber(stats.total_ratings)} icon={Star} />
                <StatsCard title={t('Avg rating')} value={stats.avg_rating > 0 ? `${stats.avg_rating.toFixed(2)} / 5` : '—'} icon={Trophy} />
            </div>

            {/* 30-day trend */}
            <Card className="mb-6">
                <CardHeader className="border-b">
                    <CardTitle className="text-base font-semibold">{t('30-day activity on your games')}</CardTitle>
                    <p className="text-xs text-muted-foreground">{t('Daily plays and comments across your approved games')}</p>
                </CardHeader>
                <CardContent className="pt-4">
                    <AuthorTrendLineChart data={trends} />
                </CardContent>
            </Card>

            {/* Pie + Top games */}
            <div className="mb-6 grid grid-cols-1 gap-4 lg:grid-cols-2">
                <Card>
                    <CardHeader className="border-b">
                        <CardTitle className="text-base font-semibold">{t('Submission status')}</CardTitle>
                        <p className="text-xs text-muted-foreground">{t('All-time breakdown across your submissions')}</p>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <SubmissionStatusPieChart
                            draft={submissions.draft}
                            pending={submissions.pending}
                            approved={submissions.approved}
                            rejected={submissions.rejected}
                        />
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="flex-row items-center justify-between border-b pb-3">
                        <CardTitle className="inline-flex items-center gap-2 text-base font-semibold">
                            <Trophy className="size-4 text-primary" />
                            {t('Top games (30d)')}
                        </CardTitle>
                        <Link href="/dashboard/authors/games" className="text-xs font-semibold text-primary hover:underline">
                            {t('All games →')}
                        </Link>
                    </CardHeader>
                    <CardContent className="p-0">
                        {top_games.length === 0 ? (
                            <p className="py-6 text-center text-sm text-muted-foreground">
                                {t('No plays in the last 30 days.')}
                            </p>
                        ) : (
                            <ol className="divide-y">
                                {top_games.map((g, i) => (
                                    <li key={g.id} className="flex items-center gap-3 px-4 py-2.5 text-sm">
                                        <span className={cn(
                                            'inline-flex size-6 shrink-0 items-center justify-center rounded-full text-[11px] font-bold',
                                            i === 0 && 'bg-amber-400/20 text-amber-600 dark:text-amber-300',
                                            i === 1 && 'bg-zinc-400/20 text-zinc-600 dark:text-zinc-300',
                                            i === 2 && 'bg-orange-400/20 text-orange-600 dark:text-orange-300',
                                            i > 2 && 'bg-muted text-muted-foreground',
                                        )}>
                                            {i + 1}
                                        </span>
                                        <Link
                                            href={`/play/${g.slug}`}
                                            target="_blank"
                                            rel="noreferrer"
                                            className="flex-1 truncate font-medium hover:underline"
                                        >
                                            {g.title}
                                        </Link>
                                        <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
                                            {t(':count plays', { count: formatNumber(g.plays_count) })}
                                        </span>
                                    </li>
                                ))}
                            </ol>
                        )}
                    </CardContent>
                </Card>
            </div>

            {/* Recent submissions + Recent comments */}
            <div className="mb-6 grid grid-cols-1 gap-4 lg:grid-cols-2">
                <Card>
                    <CardHeader className="flex-row items-center justify-between border-b pb-3">
                        <CardTitle className="inline-flex items-center gap-2 text-base font-semibold">
                            <FileText className="size-4 text-primary" />
                            {t('Recent submissions')}
                        </CardTitle>
                        <Link href="/dashboard/authors/games" className="text-xs font-semibold text-primary hover:underline">
                            {t('Manage →')}
                        </Link>
                    </CardHeader>
                    <CardContent>
                        {recent.length === 0 ? (
                            <p className="text-sm text-muted-foreground py-8 text-center">
                                {t('No submissions yet. Click "Submit new game" to get started.')}
                            </p>
                        ) : (
                            <ul className="divide-y">
                                {recent.map((row) => {
                                    const badge = STATUS_BADGE[row.submission_status];
                                    const noteLabel =
                                        row.submission_status === 'rejected'
                                            ? t('Reason')
                                            : row.submission_status === 'draft'
                                              ? t('Reviewer asked for changes')
                                              : null;
                                    const noteClass =
                                        row.submission_status === 'rejected'
                                            ? 'text-rose-600 dark:text-rose-400'
                                            : 'text-amber-700 dark:text-amber-400';
                                    return (
                                        <li key={row.id} className="flex flex-col gap-1.5 py-3 text-sm">
                                            <div className="flex items-center gap-3">
                                                <p className="font-medium truncate flex-1 min-w-0">{row.title}</p>
                                                <Badge variant="outline" className={`${badge.className} border-0`}>
                                                    {t(badge.label)}
                                                </Badge>
                                                {(row.submission_status === 'draft' || row.submission_status === 'rejected') && (
                                                    <Link
                                                        href={`/dashboard/authors/games/${row.id}/edit`}
                                                        className="text-xs font-semibold text-primary hover:underline"
                                                    >
                                                        {t('Edit →')}
                                                    </Link>
                                                )}
                                            </div>
                                            {noteLabel && row.rejection_reason && (
                                                <div className={`rounded-md bg-muted/50 border-s-2 border-current px-3 py-2 text-xs ${noteClass}`}>
                                                    <p className="font-semibold mb-0.5">{noteLabel}</p>
                                                    <p className="text-muted-foreground whitespace-pre-line">
                                                        {row.rejection_reason}
                                                    </p>
                                                </div>
                                            )}
                                        </li>
                                    );
                                })}
                            </ul>
                        )}
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="flex-row items-center justify-between border-b pb-3">
                        <CardTitle className="inline-flex items-center gap-2 text-base font-semibold">
                            <MessageSquare className="size-4 text-primary" />
                            {t('Recent comments on your games')}
                        </CardTitle>
                        <Link href="/dashboard/authors/comments" className="text-xs font-semibold text-primary hover:underline">
                            {t('Moderate →')}
                        </Link>
                    </CardHeader>
                    <CardContent className="p-0">
                        {recent_comments.length === 0 ? (
                            <p className="py-8 text-center text-sm text-muted-foreground">
                                {t('No comments yet on your games.')}
                            </p>
                        ) : (
                            <ul className="divide-y">
                                {recent_comments.map((c) => (
                                    <li key={c.id} className="px-4 py-2.5 text-sm">
                                        <p className="line-clamp-2">{c.comment}</p>
                                        <p className="mt-1 text-xs text-muted-foreground">
                                            <span className="font-medium text-foreground">{c.username}</span>
                                            {' '}{t('on')}{' '}
                                            <Link
                                                href={`/play/${c.game_slug}`}
                                                target="_blank"
                                                rel="noreferrer"
                                                className="font-medium text-foreground hover:underline"
                                            >
                                                {c.game_title}
                                            </Link>
                                            {' · '}
                                            {timeAgo(c.created_at)}
                                        </p>
                                    </li>
                                ))}
                            </ul>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}
