import type { Metadata } from "next";
import { Award, Layers, Sparkles, TrendingUp, Zap } from "lucide-react";
import { requireUser } from "@/lib/auth/rbac";
import {
  getSkillSummary,
  listSkillsWithProgress,
  type ProgressScope,
} from "@/lib/queries/progress";
import { formatNumber, formatPercent } from "@/lib/format";
import { SKILL_CATEGORY_LABEL } from "@/lib/labels";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { PageHeader, StatCard } from "@/components/ui/page-header";
import { routeCrumbs } from "@/lib/breadcrumbs";
import { Progress } from "@/components/ui/progress";
import { SkillGrid } from "@/components/progress/skill-grid";

export const metadata: Metadata = {
  title: "Keterampilan",
  description: "Keterampilan robotika dan pemrograman yang kamu kuasai.",
};

export default async function SkillsPage() {
  const user = await requireUser("/dashboard/skills");
  const scope: ProgressScope = { userId: user.id, role: user.role };

  const [skills, summary] = await Promise.all([
    listSkillsWithProgress(scope),
    getSkillSummary(scope),
  ]);

  const unlockedPercent =
    summary.total === 0 ? 0 : Math.min(100, Math.round((summary.unlocked / summary.total) * 100));

  return (
    <div className="space-y-6">
      <PageHeader
        folio="TC/LMS-27"
        crumbs={routeCrumbs("/dashboard/skills", "Keterampilan")}
        title="Keterampilan"
        description="Setiap proyek coding yang kamu lulus menambah XP keterampilan dan menaikkan levelnya."
      />

      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard
          label="Keterampilan Terbuka"
          value={`${summary.unlocked} / ${summary.total}`}
          hint={formatPercent(unlockedPercent)}
          icon={<Sparkles className="size-4" />}
        />
        <StatCard
          label="Level Tertinggi"
          value={summary.highestLevel}
          hint={summary.highestLevel === 0 ? "Belum ada level" : "Dari seluruh keterampilan"}
          icon={<Award className="size-4" />}
          tone="accent"
        />
        <StatCard
          label="XP Keterampilan"
          value={formatNumber(summary.skillXp)}
          hint="Total XP dari semua keterampilan"
          icon={<Zap className="size-4" />}
          tone="warning"
        />
        <StatCard
          label="Kategori"
          value={summary.categories.length}
          hint="Kelompok keterampilan tersedia"
          icon={<Layers className="size-4" />}
          tone="success"
        />
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Rekap per Kategori</CardTitle>
          <CardDescription>Jumlah keterampilan terbuka di setiap kategori.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {summary.categories.length === 0 ? (
            <EmptyState
              compact
              icon={<Layers className="size-4" />}
              title="Belum ada kategori"
              description="Kategori keterampilan akan muncul setelah kurikulum menyediakannya."
            />
          ) : (
            summary.categories.map((category) => {
              const percent =
                category.total === 0
                  ? 0
                  : Math.min(100, Math.round((category.unlocked / category.total) * 100));
              return (
                <div key={category.category} className="space-y-1.5">
                  <div className="flex items-center justify-between gap-2 text-sm">
                    <span className="flex min-w-0 items-center gap-2 text-primary">
                      <TrendingUp className="size-3.5 shrink-0 text-tertiary" />
                      <span className="truncate">
                        {SKILL_CATEGORY_LABEL[category.category] ?? category.category}
                      </span>
                    </span>
                    <Badge variant={percent >= 100 ? "success" : "neutral"} className="shrink-0 tabular-nums">
                      {category.unlocked}/{category.total}
                    </Badge>
                  </div>
                  <Progress
                    value={percent}
                    size="sm"
                    tone={percent >= 100 ? "success" : percent >= 50 ? "brand" : "warning"}
                  />
                </div>
              );
            })
          )}
        </CardContent>
      </Card>

      <SkillGrid skills={skills} />
    </div>
  );
}
