"use client";

import * as React from "react";
import { useActionState } from "react";
import { Plus, Trash2, TriangleAlert } from "lucide-react";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Field, Input, Select, Textarea } from "@/components/ui/input";
import { CodeEditor } from "@/components/coding/code-editor";
import { createCodingProjectAction } from "@/actions/coding";
import { IDLE_ACTION } from "@/lib/action-state";

interface TestDraft {
  key: string;
  name: string;
  body: string;
}

/**
 * Authoring form for a coding project.
 *
 * Tests are authored as parallel `testName[]` / `testBody[]` fields, which the
 * server action zips back together. Each test body is appended to the learner's
 * code, so it should call `assert(...)` or `assertEqual(...)`.
 */
export function CodingProjectForm({
  courses,
  skills,
}: {
  courses: { id: string; title: string }[];
  skills: { id: string; name: string; icon: string; color: string }[];
}) {
  const [state, formAction, pending] = useActionState(createCodingProjectAction, IDLE_ACTION);

  const [language, setLanguage] = React.useState<"JAVASCRIPT" | "PYTHON" | "ROBOT">("JAVASCRIPT");
  const [starterCode, setStarterCode] = React.useState(
    "function solusi(input) {\n  // tulis kodemu di sini\n}\n"
  );
  const [tests, setTests] = React.useState<TestDraft[]>([
    {
      key: "initial",
      name: "Contoh pengujian",
      body: 'assertEqual(solusi(2), 4, "solusi(2) seharusnya 4");',
    },
  ]);

  const errors = state.status === "error" ? state.errors : undefined;

  function addTest() {
    setTests((current) => [
      ...current,
      { key: `test-${Date.now()}-${current.length}`, name: "", body: "" },
    ]);
  }

  function removeTest(key: string) {
    setTests((current) => current.filter((test) => test.key !== key));
  }

  function updateTest(key: string, patch: Partial<TestDraft>) {
    setTests((current) =>
      current.map((test) => (test.key === key ? { ...test, ...patch } : test))
    );
  }

  const exampleAssert =
    language === "PYTHON"
      ? 'assert solusi(2) == 4, "solusi(2) seharusnya 4"'
      : 'assertEqual(solusi(2), 4, "solusi(2) seharusnya 4");';

  return (
    <form action={formAction} className="space-y-6">
      {state.status === "error" && state.message ? (
        <Alert tone="danger" icon={<TriangleAlert className="size-4" />}>
          {state.message}
        </Alert>
      ) : null}
      {state.status === "success" && state.message ? (
        <Alert tone="success">{state.message}</Alert>
      ) : null}

      <Card>
        <CardHeader>
          <CardTitle>Informasi Proyek</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <Field label="Judul" htmlFor="project-title" required error={errors?.title}>
            <Input
              id="project-title"
              name="title"
              required
              placeholder="mis. Fungsi Menghitung Rata-rata"
            />
          </Field>

          <Field
            label="Deskripsi Singkat"
            htmlFor="project-description"
            error={errors?.description}
          >
            <Textarea
              id="project-description"
              name="description"
              rows={2}
              placeholder="Muncul pada daftar proyek."
            />
          </Field>

          <Field
            label="Ringkasan Tugas"
            htmlFor="project-brief"
            hint="Penjelasan lengkap yang dibaca siswa di halaman proyek."
            error={errors?.brief}
          >
            <Textarea
              id="project-brief"
              name="brief"
              rows={5}
              placeholder="Jelaskan apa yang harus dibuat, masukan, dan keluarannya."
            />
          </Field>

          <div className="grid gap-4 sm:grid-cols-4">
            <Field label="Bahasa" htmlFor="project-language">
              <Select
                id="project-language"
                name="language"
                value={language}
                onChange={(event) =>
                  setLanguage(event.target.value as "JAVASCRIPT" | "PYTHON" | "ROBOT")
                }
              >
                <option value="JAVASCRIPT">JavaScript</option>
                <option value="PYTHON">Python</option>
                <option value="ROBOT">Robot</option>
              </Select>
            </Field>

            <Field label="Tingkat" htmlFor="project-difficulty">
              <Select id="project-difficulty" name="difficulty" defaultValue="BEGINNER">
                <option value="BEGINNER">Pemula</option>
                <option value="INTERMEDIATE">Menengah</option>
                <option value="ADVANCED">Mahir</option>
              </Select>
            </Field>

            <Field label="Hadiah XP" htmlFor="project-xp">
              <Input id="project-xp" name="xpReward" type="number" min={0} max={1000} defaultValue={50} />
            </Field>

            <Field label="Status" htmlFor="project-status">
              <Select id="project-status" name="status" defaultValue="DRAFT">
                <option value="DRAFT">Draf</option>
                <option value="PUBLISHED">Terbit</option>
                <option value="ARCHIVED">Diarsipkan</option>
              </Select>
            </Field>
          </div>

          <div className="grid gap-4 sm:grid-cols-2">
            <Field label="Kursus" htmlFor="project-course" hint="Opsional.">
              <Select id="project-course" name="courseId" defaultValue="">
                <option value="">Tanpa kursus</option>
                {courses.map((course) => (
                  <option key={course.id} value={course.id}>
                    {course.title}
                  </option>
                ))}
              </Select>
            </Field>

            <Field label="Petunjuk" htmlFor="project-hints" hint="Satu petunjuk per baris.">
              <Textarea id="project-hints" name="hints" rows={3} />
            </Field>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Keterampilan yang Diberikan</CardTitle>
          <p className="text-sm text-secondary">
            Siswa mendapat XP keterampilan ini saat proyek berhasil diselesaikan.
          </p>
        </CardHeader>
        <CardContent>
          {skills.length === 0 ? (
            <p className="text-sm text-tertiary">Belum ada keterampilan terdaftar.</p>
          ) : (
            <div className="flex flex-wrap gap-3">
              {skills.map((skill) => (
                <label
                  key={skill.id}
                  className="flex cursor-pointer items-center gap-2 rounded-lg border border-subtle px-3 py-2 text-sm hover:bg-hover"
                >
                  <input type="checkbox" name="skillIds[]" value={skill.id} />
                  <span style={{ color: skill.color }} aria-hidden="true">
                    ●
                  </span>
                  {skill.name}
                </label>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Kode Awal</CardTitle>
          <p className="text-sm text-secondary">
            Kode yang sudah terisi saat siswa membuka proyek.
          </p>
        </CardHeader>
        <CardContent className="space-y-3">
          <CodeEditor
            value={starterCode}
            onChange={setStarterCode}
            language={language}
            minHeight="14rem"
            ariaLabel="Kode awal"
          />
          <input type="hidden" name="starterCode" value={starterCode} />

          <Field label="Kode Solusi" htmlFor="project-solution" hint="Opsional, untuk penulis.">
            <Textarea
              id="project-solution"
              name="solutionCode"
              rows={5}
              className="font-mono text-xs"
              placeholder="Solusi referensi yang tidak ditampilkan ke siswa."
            />
          </Field>
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex-row flex-wrap items-center justify-between gap-3">
          <div className="space-y-1">
            <CardTitle>Pengujian Otomatis</CardTitle>
            <p className="text-sm text-secondary">
              Setiap pengujian dijalankan terpisah. Gunakan{" "}
              <code className="rounded bg-sunken px-1 text-xs">{exampleAssert}</code>.
            </p>
          </div>
          <Button type="button" variant="secondary" onClick={addTest}>
            <Plus className="size-4" />
            Tambah Pengujian
          </Button>
        </CardHeader>
        <CardContent className="space-y-4">
          {errors?.tests ? <Alert tone="danger">{errors.tests}</Alert> : null}

          {tests.map((test, index) => (
            <div key={test.key} className="space-y-3 rounded-lg border border-subtle p-4">
              <div className="flex items-center justify-between gap-3">
                <span className="text-xs font-medium text-tertiary">Pengujian {index + 1}</span>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon-sm"
                  aria-label={`Hapus pengujian ${index + 1}`}
                  onClick={() => removeTest(test.key)}
                  disabled={tests.length === 1}
                >
                  <Trash2 className="size-3.5" />
                </Button>
              </div>

              <Field label="Nama Pengujian" htmlFor={`test-name-${test.key}`}>
                <Input
                  id={`test-name-${test.key}`}
                  name="testName[]"
                  value={test.name}
                  onChange={(event) => updateTest(test.key, { name: event.target.value })}
                  placeholder="mis. Menghitung rata-rata dua angka"
                />
              </Field>

              <Field label="Kode Pengujian" htmlFor={`test-body-${test.key}`}>
                <Textarea
                  id={`test-body-${test.key}`}
                  name="testBody[]"
                  rows={3}
                  value={test.body}
                  onChange={(event) => updateTest(test.key, { body: event.target.value })}
                  className="font-mono text-xs"
                  placeholder={exampleAssert}
                />
              </Field>
            </div>
          ))}
        </CardContent>
      </Card>

      <div className="flex justify-end gap-2">
        <Button type="submit" loading={pending}>
          Simpan Proyek
        </Button>
      </div>
    </form>
  );
}
