import type { Metadata } from "next";
import { notFound } from "next/navigation";
import {Bot, CheckCircle2, Flag, Star, Timer, Trophy } from "lucide-react";
import { requireUser } from "@/lib/auth/rbac";
import { getSimulatorChallenge } from "@/lib/queries/coding";
import { formatRelativeTime } from "@/lib/format";
import { LEVEL_BADGE, PUBLISH_BADGE } from "@/lib/labels";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { PageHeader, StatCard } from "@/components/ui/page-header";
import { SimulatorWorkspace } from "@/components/coding/simulator-workspace";
import { configFromChallenge, type Direction } from "@/lib/simulator";
import { routeCrumbs } from "@/lib/breadcrumbs";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ challengeId: string }>;
}): Promise<Metadata> {
  const { challengeId } = await params;
  const user = await requireUser(`/dashboard/lab/${challengeId}`);
  const challenge = await getSimulatorChallenge(
    { userId: user.id, role: user.role },
    challengeId
  );
  return { title: challenge?.title ?? "Misi Simulator" };
}

export default async function SimulatorChallengePage({
  params,
}: {
  params: Promise<{ challengeId: string }>;
}) {
  const { challengeId } = await params;
  const user = await requireUser(`/dashboard/lab/${challengeId}`);

  const challenge = await getSimulatorChallenge(
    { userId: user.id, role: user.role },
    challengeId
  );
  if (!challenge) notFound();

  // The client and server share one interpreter, so the config is derived the
  // same way on both sides via `configFromChallenge`.
  const config = configFromChallenge(challenge);
  const solved = challenge.myAttempts.some((attempt) => attempt.success);
  const bestAttempt = challenge.myAttempts.find((attempt) => attempt.success) ?? null;

  return (
    <div className="space-y-6">
      <PageHeader
        folio="TC/LMS-21"
        crumbs={routeCrumbs(`/dashboard/lab/${challenge.id}`, challenge.title)}
        title={challenge.title}
        description={challenge.description}
        actions={
          solved ? (
            <Badge variant="success">
              <CheckCircle2 className="size-3" />
              Misi Selesai
            </Badge>
          ) : null
        }
      />

      <div className="flex flex-wrap items-center gap-2">
        <Badge variant={LEVEL_BADGE[challenge.difficulty].variant}>
          {LEVEL_BADGE[challenge.difficulty].label}
        </Badge>
        <Badge variant="neutral">
          <Flag className="size-3" />
          Grid {challenge.gridWidth}×{challenge.gridHeight}
        </Badge>
        <Badge variant="neutral">
          <Star className="size-3" />
          {challenge.stars.length} bintang
        </Badge>
        <Badge variant="neutral">
          <Timer className="size-3" />
          Par {challenge.parSteps} langkah
        </Badge>
        <Badge variant="accent">
          <Trophy className="size-3" />
          +{challenge.xpReward} XP
        </Badge>
        {challenge.canManage && challenge.status !== "PUBLISHED" ? (
          <Badge variant={PUBLISH_BADGE[challenge.status].variant}>
            {PUBLISH_BADGE[challenge.status].label}
          </Badge>
        ) : null}
      </div>

      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard
          label="Percobaanmu"
          value={challenge.myAttempts.length}
          hint={
            challenge.myAttempts[0]
              ? `Terakhir ${formatRelativeTime(challenge.myAttempts[0].createdAt)}`
              : "Belum pernah mencoba"
          }
          icon={<Bot className="size-4" />}
        />
        <StatCard
          label="Status"
          value={solved ? "Selesai" : "Belum"}
          hint={solved ? "Misi berhasil diselesaikan" : "Capai tujuan untuk menyelesaikan"}
          icon={<Flag className="size-4" />}
          tone={solved ? "success" : "warning"}
        />
        <StatCard
          label="Langkah Terbaik"
          value={bestAttempt ? bestAttempt.stepsUsed : "—"}
          hint={`Par ${challenge.parSteps} langkah`}
          icon={<Timer className="size-4" />}
          tone={
            bestAttempt && bestAttempt.stepsUsed <= challenge.parSteps ? "success" : "brand"
          }
        />
        <StatCard
          label="Skor Terbaik"
          value={bestAttempt ? bestAttempt.score : "—"}
          hint={bestAttempt ? `${bestAttempt.starsEarned} bintang terkumpul` : "Belum ada skor"}
          icon={<Trophy className="size-4" />}
          tone="accent"
        />
      </div>

      <SimulatorWorkspace
        challengeId={challenge.id}
        config={config}
        spec={{
          width: challenge.gridWidth,
          height: challenge.gridHeight,
          walls: challenge.walls,
          stars: challenge.stars,
          goal: { x: challenge.goalX, y: challenge.goalY },
        }}
        starterCode={challenge.starterCode}
        initialProgram={challenge.myAttempts[0]?.program ?? ""}
        hints={challenge.hints}
        parSteps={challenge.parSteps}
        maxSteps={challenge.maxSteps}
        xpReward={challenge.xpReward}
        solutionCode={challenge.canManage ? challenge.solutionCode : null}
      />

      {challenge.myAttempts.length > 0 ? (
        <Card>
          <CardHeader>
            <CardTitle>Riwayat Misi</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {challenge.myAttempts.map((attempt) => (
                <div
                  key={attempt.id}
                  className="flex flex-wrap items-center gap-3 rounded-lg border border-subtle p-3 text-sm"
                >
                  <Badge variant={attempt.success ? "success" : "danger"}>
                    {attempt.success ? "Berhasil" : "Gagal"}
                  </Badge>
                  <span className="text-secondary">{attempt.stepsUsed} langkah</span>
                  <span className="text-secondary">{attempt.starsEarned} bintang</span>
                  <span className="ml-auto text-xs text-tertiary">
                    {formatRelativeTime(attempt.createdAt)}
                  </span>
                  <span className="font-medium tabular-nums text-primary">{attempt.score}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      ) : null}

      <p className="text-xs text-tertiary">
        Arah awal robot: {challenge.startDir as Direction}. Simulator berjalan di browser dengan
        mesin yang sama seperti validasi server.
      </p>
    </div>
  );
}
