"use client";

import * as React from "react";
import { useActionState } from "react";
import {
  CheckCircle2,
  CircleX,
  Lightbulb,
  Play,
  RotateCcw,
  Send,
  Terminal,
  TriangleAlert,
} 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 { CodeEditor } from "@/components/coding/code-editor";
import {
  executeCodingSnippetAction,
  runCodingProjectAction,
} from "@/actions/coding";
import { IDLE_ACTION } from "@/lib/action-state";
import { CODING_STATUS_BADGE, LANGUAGE_LABEL } from "@/lib/labels";
import type { CodingLanguage } from "@prisma/client";

export interface CodingWorkspaceTest {
  name: string;
  test: string;
}

export interface CodingWorkspaceAttempt {
  id: string;
  status: string;
  score: number;
  passedTests: number;
  totalTests: number;
  createdAt: Date;
}

/**
 * The coding workspace.
 *
 * Two distinct actions, matching the two buttons:
 *   • "Jalankan" — `executeCodingSnippetAction`, persists a RUNNING attempt so
 *     the learner's exploration is recorded but no XP is paid.
 *   • "Kirim Jawaban" — `runCodingProjectAction`, asserts the full suite and
 *     awards XP/skills on success.
 *
 * Local state is seeded from the project's starter code, falling back to the
 * learner's most recent submission so returning to a project resumes their work.
 */
export function CodingWorkspace({
  projectId,
  language,
  starterCode,
  initialCode,
  hints,
  tests,
  attempts,
  solutionCode,
}: {
  projectId: string;
  language: CodingLanguage;
  starterCode: string;
  initialCode: string;
  hints: string[];
  tests: CodingWorkspaceTest[];
  attempts: CodingWorkspaceAttempt[];
  solutionCode: string | null;
}) {
  const [code, setCode] = React.useState(initialCode || starterCode);
  const [revealedHints, setRevealedHints] = React.useState(0);
  const [showSolution, setShowSolution] = React.useState(false);

  const [runState, runAction, runPending] = useActionState(
    executeCodingSnippetAction,
    IDLE_ACTION
  );
  const [submitState, submitAction, submitPending] = useActionState(
    runCodingProjectAction,
    IDLE_ACTION
  );

  const pending = runPending || submitPending;
  const busy = pending;

  // The most recent graded attempt drives the result panel.
  const latestAttempt = attempts[0] ?? null;

  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>Editor Kode</CardTitle>
              <p className="text-sm text-secondary">
                {LANGUAGE_LABEL[language]} · {tests.length} pengujian otomatis
              </p>
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => setCode(starterCode)}
                disabled={busy}
              >
                <RotateCcw className="size-3.5" />
                Reset Kode
              </Button>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <CodeEditor
              value={code}
              onChange={setCode}
              language={language}
              minHeight="24rem"
              ariaLabel="Editor kode"
            />

            <div className="flex flex-wrap items-center gap-2">
              <form action={runAction} className="contents">
                <input type="hidden" name="projectId" value={projectId} />
                <input type="hidden" name="code" value={code} />
                <Button type="submit" variant="secondary" loading={runPending} disabled={busy}>
                  <Play className="size-4" />
                  Jalankan
                </Button>
              </form>

              <form action={submitAction} className="contents">
                <input type="hidden" name="projectId" value={projectId} />
                <input type="hidden" name="code" value={code} />
                <Button type="submit" loading={submitPending} disabled={busy}>
                  <Send className="size-4" />
                  Kirim Jawaban
                </Button>
              </form>

              <span className="ml-auto text-xs text-tertiary">
                {code.length.toLocaleString("id-ID")} karakter
              </span>
            </div>

            {submitState.status === "success" && submitState.message ? (
              <Alert tone="success" icon={<CheckCircle2 className="size-4" />}>
                {submitState.message}
              </Alert>
            ) : null}

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

            {runState.status === "error" && runState.message ? (
              <Alert tone="warning" icon={<TriangleAlert className="size-4" />}>
                {runState.message}
              </Alert>
            ) : null}

            {runState.status === "success" && runState.message ? (
              <Alert tone="info">{runState.message}</Alert>
            ) : null}
          </CardContent>
        </Card>

        {latestAttempt ? (
          <Card>
            <CardHeader className="flex-row items-center justify-between gap-3">
              <CardTitle>Hasil Terakhir</CardTitle>
              <Badge
                variant={
                  CODING_STATUS_BADGE[latestAttempt.status as keyof typeof CODING_STATUS_BADGE]
                    ?.variant ?? "neutral"
                }
              >
                {CODING_STATUS_BADGE[latestAttempt.status as keyof typeof CODING_STATUS_BADGE]
                  ?.label ?? latestAttempt.status}
              </Badge>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="flex items-center gap-3">
                <span className="text-3xl font-bold tabular-nums text-primary">
                  {latestAttempt.score}
                </span>
                <span className="text-sm text-tertiary">
                  / 100 · {latestAttempt.passedTests}/{latestAttempt.totalTests} pengujian lulus
                </span>
              </div>

              <div className="space-y-1.5">
                {tests.map((test, index) => {
                  const passed = index < latestAttempt.passedTests;
                  return (
                    <div
                      key={`${test.name}-${index}`}
                      className="flex items-center gap-2 rounded-md border border-subtle px-3 py-2 text-sm"
                    >
                      {passed ? (
                        <CheckCircle2 className="size-4 shrink-0 text-success-600 dark:text-success-500" />
                      ) : (
                        <CircleX className="size-4 shrink-0 text-danger-600 dark:text-danger-500" />
                      )}
                      <span className="min-w-0 flex-1 truncate text-primary">{test.name}</span>
                      <span className="shrink-0 text-xs text-tertiary">
                        {passed ? "Lulus" : "Belum lulus"}
                      </span>
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>
        ) : null}
      </div>

      <div className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Petunjuk</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            {hints.length === 0 ? (
              <p className="text-sm text-tertiary">Tidak ada petunjuk untuk proyek 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={language}
                  readOnly
                  minHeight="14rem"
                  ariaLabel="Kode solusi"
                />
              ) : (
                <>
                  <p className="text-sm text-secondary">
                    Coba selesaikan sendiri terlebih dahulu. Membuka solusi akan mengurangi nilai
                    pengalaman belajarmu.
                  </p>
                  <Button
                    type="button"
                    variant="secondary"
                    size="sm"
                    onClick={() => setShowSolution(true)}
                  >
                    Tampilkan Solusi
                  </Button>
                </>
              )}
            </CardContent>
          </Card>
        ) : null}

        <Card>
          <CardHeader>
            <CardTitle>Riwayat Percobaan</CardTitle>
          </CardHeader>
          <CardContent>
            {attempts.length === 0 ? (
              <p className="text-sm text-tertiary">
                Belum ada percobaan. Jalankan kodemu untuk memulai.
              </p>
            ) : (
              <ol className="space-y-2">
                {attempts.map((attempt) => {
                  const badge =
                    CODING_STATUS_BADGE[attempt.status as keyof typeof CODING_STATUS_BADGE];
                  return (
                    <li
                      key={attempt.id}
                      className="flex items-center justify-between gap-2 border-b border-subtle pb-2 text-sm last:border-0 last:pb-0"
                    >
                      <span className="text-tertiary">
                        {new Date(attempt.createdAt).toLocaleString("id-ID", {
                          day: "numeric",
                          month: "short",
                          hour: "2-digit",
                          minute: "2-digit",
                        })}
                      </span>
                      {badge ? <Badge variant={badge.variant}>{badge.label}</Badge> : null}
                      <span className="tabular-nums text-secondary">{attempt.score}</span>
                    </li>
                  );
                })}
              </ol>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Output</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-start gap-2 border border-subtle bg-brand-950 p-3 font-mono text-xs text-doc-paper">
              <Terminal className="mt-0.5 size-3.5 shrink-0 text-doc-ink-3" />
              <span className="whitespace-pre-wrap break-all">
                {latestAttempt
                  ? `Status: ${latestAttempt.status}\nSkor: ${latestAttempt.score}\nPengujian: ${latestAttempt.passedTests}/${latestAttempt.totalTests}`
                  : "Belum ada output."}
              </span>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
