"use client";

import * as React from "react";
import { useActionState } from "react";
import {
  ChevronLeft,
  ChevronRight,
  CircleX,
  Lightbulb,
  Pause,
  Play,
  RotateCcw,
  Send,
  StepForward,
  Timer,
  Trophy,
} from "lucide-react";
import { Alert } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { CodeEditor } from "@/components/coding/code-editor";
import { SimulatorGrid, type GridSpec } from "@/components/coding/simulator-grid";
import { runSimulatorAction } from "@/actions/coding";
import { IDLE_ACTION } from "@/lib/action-state";
import {
  DIRECTION_LABELS,
  runSimulator,
  type Direction,
  type SimulatorConfig,
  type TraceFrame,
} from "@/lib/simulator";

/**
 * Robot simulator playground.
 *
 * The program is interpreted **client-side** with the same pure interpreter the
 * server uses (`runSimulator`), which gives instant feedback and lets us animate
 * the recorded trace. Submitting persists the attempt and awards XP through the
 * server action, so the database remains the source of truth for progress.
 */
export function SimulatorWorkspace({
  challengeId,
  config,
  spec,
  starterCode,
  initialProgram,
  hints,
  parSteps,
  maxSteps,
  xpReward,
  solutionCode,
}: {
  challengeId: string;
  config: SimulatorConfig;
  spec: GridSpec;
  starterCode: string;
  initialProgram: string;
  hints: string[];
  parSteps: number;
  maxSteps: number;
  xpReward: number;
  solutionCode: string | null;
}) {
  const [program, setProgram] = React.useState(initialProgram || starterCode);
  const [revealedHints, setRevealedHints] = React.useState(0);
  const [showSolution, setShowSolution] = React.useState(false);
  const [frameIndex, setFrameIndex] = React.useState(0);
  const [playing, setPlaying] = React.useState(false);

  const [submitState, submitAction, submitPending] = useActionState(
    runSimulatorAction,
    IDLE_ACTION
  );

  // Re-interpret on every edit: the program is small and the interpreter is pure.
  const result = React.useMemo(() => {
    if (!program.trim()) return null;
    return runSimulator(program, config);
  }, [program, config]);

  const trace: TraceFrame[] = result?.trace ?? [];
  const currentFrame: TraceFrame | null = trace[Math.min(frameIndex, Math.max(0, trace.length - 1))] ?? null;

  // Reset the scrubber whenever a new interpretation lands.
  React.useEffect(() => {
    setFrameIndex(0);
    setPlaying(false);
  }, [result]);

  // Step through the trace while playing.
  React.useEffect(() => {
    if (!playing) return;
    if (frameIndex >= trace.length - 1) {
      setPlaying(false);
      return;
    }
    const timer = setTimeout(() => setFrameIndex((index) => index + 1), 320);
    return () => clearTimeout(timer);
  }, [playing, frameIndex, trace.length]);

  // Fall back to the configured start position before the first frame runs.
  const robotX = currentFrame?.x ?? config.startX;
  const robotY = currentFrame?.y ?? config.startY;
  const robotDir: Direction = currentFrame?.dir ?? (config.startDir as Direction);
  const collected = currentFrame?.collected ?? [];
  const blocked = currentFrame?.blocked ?? false;

  const stepsUsed = result?.stepsUsed ?? 0;
  const starsCollected = result?.starsCollected ?? 0;
  const totalStars = result?.totalStars ?? 0;

  return (
    <div className="grid gap-6 lg:grid-cols-3">
      <div className="space-y-4 lg:col-span-2">
        <Card>
          <CardHeader className="flex-row flex-wrap items-center justify-between gap-3">
            <div className="space-y-1">
              <CardTitle>Dunia Robot</CardTitle>
              <p className="text-sm text-secondary">
                {spec.width}×{spec.height} · par {parSteps} langkah · maksimal {maxSteps} langkah
              </p>
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <Badge variant="neutral">
                <StepForward className="size-3" />
                {stepsUsed} langkah
              </Badge>
              <Badge variant={starsCollected === totalStars && totalStars > 0 ? "success" : "neutral"}>
                <Trophy className="size-3" />
                {starsCollected}/{totalStars} bintang
              </Badge>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex justify-center">
              <SimulatorGrid
                spec={spec}
                x={robotX}
                y={robotY}
                dir={robotDir}
                collected={collected}
                blocked={blocked}
              />
            </div>

            {trace.length > 0 ? (
              <div className="space-y-3">
                <div className="flex flex-wrap items-center justify-center gap-2">
                  <Button
                    type="button"
                    variant="secondary"
                    size="icon-sm"
                    aria-label="Langkah sebelumnya"
                    disabled={frameIndex === 0}
                    onClick={() => setFrameIndex((index) => Math.max(0, index - 1))}
                  >
                    <ChevronLeft className="size-3.5" />
                  </Button>

                  <Button
                    type="button"
                    variant={playing ? "secondary" : "primary"}
                    size="sm"
                    onClick={() => setPlaying((value) => !value)}
                  >
                    {playing ? <Pause className="size-3.5" /> : <Play className="size-3.5" />}
                    {playing ? "Jeda" : "Putar"}
                  </Button>

                  <Button
                    type="button"
                    variant="secondary"
                    size="icon-sm"
                    aria-label="Langkah berikutnya"
                    disabled={frameIndex >= trace.length - 1}
                    onClick={() => setFrameIndex((index) => Math.min(trace.length - 1, index + 1))}
                  >
                    <ChevronRight className="size-3.5" />
                  </Button>

                  <Button
                    type="button"
                    variant="ghost"
                    size="icon-sm"
                    aria-label="Ulang dari awal"
                    onClick={() => {
                      setFrameIndex(0);
                      setPlaying(false);
                    }}
                  >
                    <RotateCcw className="size-3.5" />
                  </Button>
                </div>

                <div className="space-y-1.5">
                  <input
                    type="range"
                    min={0}
                    max={Math.max(0, trace.length - 1)}
                    value={frameIndex}
                    onChange={(event) => {
                      setPlaying(false);
                      setFrameIndex(Number(event.target.value));
                    }}
                    aria-label="Geser posisi animasi"
                    className="w-full accent-brand-600"
                  />
                  <p className="text-center text-xs text-tertiary">
                    Langkah {frameIndex + 1} dari {trace.length}
                    {currentFrame ? ` · ${currentFrame.action} · ${DIRECTION_LABELS[currentFrame.dir]}` : ""}
                  </p>
                </div>
              </div>
            ) : null}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Program Robot</CardTitle>
            <p className="text-sm text-secondary">
              Perintah: <code className="rounded bg-sunken px-1">move</code>,{" "}
              <code className="rounded bg-sunken px-1">turnLeft</code>,{" "}
              <code className="rounded bg-sunken px-1">turnRight</code>,{" "}
              <code className="rounded bg-sunken px-1">pick</code>, serta{" "}
              <code className="rounded bg-sunken px-1">repeat</code> dan{" "}
              <code className="rounded bg-sunken px-1">if</code>.
            </p>
          </CardHeader>
          <CardContent className="space-y-4">
            <CodeEditor
              value={program}
              onChange={setProgram}
              language="ROBOT"
              minHeight="16rem"
              ariaLabel="Editor program robot"
            />

            <form action={submitAction} className="flex flex-wrap items-center gap-2">
              <input type="hidden" name="challengeId" value={challengeId} />
              <input type="hidden" name="program" value={program} />
              <Button type="submit" loading={submitPending} disabled={!program.trim()}>
                <Send className="size-4" />
                Kirim &amp; Simpan
              </Button>
              <Button
                type="button"
                variant="ghost"
                onClick={() => setProgram(starterCode)}
                disabled={submitPending}
              >
                <RotateCcw className="size-4" />
                Reset Program
              </Button>
            </form>

            {submitState.status === "success" && submitState.message ? (
              <Alert tone="success">{submitState.message}</Alert>
            ) : null}
            {submitState.status === "error" && submitState.message ? (
              <Alert tone="danger" icon={<CircleX className="size-4" />}>
                {submitState.message}
              </Alert>
            ) : null}
          </CardContent>
        </Card>
      </div>

      <div className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Status Misi</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {!result ? (
              <p className="text-sm text-tertiary">Tulis program untuk melihat hasilnya.</p>
            ) : result.error ? (
              <Alert tone="danger" icon={<CircleX className="size-4" />}>
                {result.error}
                {result.errorLine ? ` (baris ${result.errorLine})` : ""}
              </Alert>
            ) : (
              <>
                <div className="space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-secondary">Bintang</span>
                    <span className="font-medium tabular-nums text-primary">
                      {starsCollected}/{totalStars}
                    </span>
                  </div>
                  <Progress
                    value={totalStars === 0 ? 100 : (starsCollected / totalStars) * 100}
                    size="sm"
                    tone="warning"
                  />
                </div>

                <div className="space-y-2">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-secondary">Efisiensi langkah</span>
                    <span className="font-medium tabular-nums text-primary">
                      {stepsUsed}/{maxSteps}
                    </span>
                  </div>
                  <Progress
                    value={(stepsUsed / maxSteps) * 100}
                    size="sm"
                    tone={stepsUsed <= parSteps ? "success" : "brand"}
                  />
                  {stepsUsed <= parSteps ? (
                    <p className="flex items-center gap-1 text-xs text-success-600 dark:text-success-500">
                      <Timer className="size-3" />
                      Sama atau lebih efisien dari par!
                    </p>
                  ) : null}
                </div>

                <div className="rounded-lg bg-sunken p-3">
                  <p className="text-sm font-medium text-primary">
                    {result.success ? "Misi berhasil!" : "Belum berhasil"}
                  </p>
                  <p className="mt-1 text-xs text-secondary">{result.message}</p>
                  <p className="mt-2 text-xs text-tertiary">
                    Skor sementara: <strong className="text-primary">{result.score}</strong>
                  </p>
                </div>
              </>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Petunjuk</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            {hints.length === 0 ? (
              <p className="text-sm text-tertiary">Tidak ada petunjuk untuk misi ini.</p>
            ) : (
              <>
                {hints.slice(0, revealedHints).map((hint, index) => (
                  <div key={index} className="rounded-lg bg-sunken p-3">
                    <p className="text-xs font-medium text-secondary">Petunjuk {index + 1}</p>
                    <p className="mt-1 text-sm text-primary">{hint}</p>
                  </div>
                ))}
                {revealedHints < hints.length ? (
                  <Button
                    type="button"
                    variant="secondary"
                    size="sm"
                    onClick={() => setRevealedHints((count) => count + 1)}
                  >
                    <Lightbulb className="size-4" />
                    Buka Petunjuk ({revealedHints}/{hints.length})
                  </Button>
                ) : null}
              </>
            )}
          </CardContent>
        </Card>

        {solutionCode ? (
          <Card>
            <CardHeader>
              <CardTitle>Solusi</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              {showSolution ? (
                <CodeEditor
                  value={solutionCode}
                  onChange={() => {}}
                  language="ROBOT"
                  readOnly
                  minHeight="12rem"
                  ariaLabel="Program solusi"
                />
              ) : (
                <>
                  <p className="text-sm text-secondary">
                    Coba selesaikan sendiri terlebih dahulu sebelum melihat solusinya.
                  </p>
                  <Button
                    type="button"
                    variant="secondary"
                    size="sm"
                    onClick={() => setShowSolution(true)}
                  >
                    Tampilkan Solusi
                  </Button>
                </>
              )}
            </CardContent>
          </Card>
        ) : null}

        <Card>
          <CardContent className="pt-5">
            <p className="text-xs text-tertiary">
              Hadiah misi ini <strong className="text-primary">+{xpReward} XP</strong>, diberikan
              sekali saat misi berhasil diselesaikan.
            </p>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
