"use client";

import * as React from "react";
import { useActionState } from "react";
import { Plus, TriangleAlert } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Field, Input, Select, Textarea } from "@/components/ui/input";
import { Alert } from "@/components/ui/alert";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { createCourseAction, updateCourseAction } from "@/actions/courses";
import { IDLE_ACTION } from "@/lib/action-state";

const LEVELS = [
  { value: "BEGINNER", label: "Pemula" },
  { value: "INTERMEDIATE", label: "Menengah" },
  { value: "ADVANCED", label: "Mahir" },
];

const LANGUAGES = [
  { value: "JAVASCRIPT", label: "JavaScript" },
  { value: "PYTHON", label: "Python" },
  { value: "ROBOT", label: "Robot" },
];

const STATUSES = [
  { value: "DRAFT", label: "Draf" },
  { value: "PUBLISHED", label: "Terbit" },
  { value: "ARCHIVED", label: "Diarsipkan" },
];

const COLORS = ["#26241c", "#d93a0b", "#2f7d52", "#b07908", "#c0392b", "#2c6e8f", "#6b675c"];

export interface CourseFormValues {
  id: string;
  title: string;
  summary: string | null;
  description: string | null;
  level: string;
  language: string;
  status: string;
  estimatedHours: number;
  coverColor: string;
  tags: string[];
  classroomId: string | null;
}

/**
 * Create/edit dialog for a course.
 *
 * One component serves both modes because the field set is identical; only the
 * action and the initial values differ.
 */
export function CourseFormDialog({
  mode,
  course,
  classrooms,
  trigger,
}: {
  mode: "create" | "edit";
  course?: CourseFormValues;
  classrooms: { id: string; name: string }[];
  trigger?: React.ReactNode;
}) {
  const [open, setOpen] = React.useState(false);
  const action = mode === "create" ? createCourseAction : updateCourseAction;
  const [state, formAction, pending] = useActionState(action, IDLE_ACTION);
  const [color, setColor] = React.useState(course?.coverColor ?? COLORS[0]);

  // Close and reset once the action reports success.
  React.useEffect(() => {
    if (state.status === "success") setOpen(false);
  }, [state.status]);

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

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {trigger ?? (
          <Button>
            <Plus className="size-4" />
            Kursus Baru
          </Button>
        )}
      </DialogTrigger>

      <DialogContent size="lg">
        <form action={formAction} className="flex min-h-0 flex-1 flex-col">
          {course ? <input type="hidden" name="courseId" value={course.id} /> : null}
          <input type="hidden" name="coverColor" value={color} />

          <DialogHeader>
            <DialogTitle>{mode === "create" ? "Buat Kursus" : "Ubah Kursus"}</DialogTitle>
            <DialogDescription>
              {mode === "create"
                ? "Kursus baru dimulai sebagai draf. Terbitkan saat sudah siap."
                : "Perbarui informasi kursus ini."}
            </DialogDescription>
          </DialogHeader>

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

            <Field label="Judul Kursus" htmlFor="title" required error={errors?.title}>
              <Input
                id="title"
                name="title"
                defaultValue={course?.title}
                placeholder="mis. Robotika Dasar: Sensor dan Aktuator"
                required
                autoFocus
              />
            </Field>

            <Field
              label="Ringkasan"
              htmlFor="summary"
              hint="Satu kalimat yang muncul di daftar kursus."
              error={errors?.summary}
            >
              <Input
                id="summary"
                name="summary"
                defaultValue={course?.summary ?? ""}
                placeholder="Pengenalan sensor dan aktuator untuk robotika."
              />
            </Field>

            <Field label="Deskripsi" htmlFor="description" error={errors?.description}>
              <Textarea
                id="description"
                name="description"
                rows={4}
                defaultValue={course?.description ?? ""}
                placeholder="Jelaskan cakupan, prasyarat, dan hasil belajar kursus ini."
              />
            </Field>

            <div className="grid gap-4 sm:grid-cols-3">
              <Field label="Tingkat" htmlFor="level" error={errors?.level}>
                <Select id="level" name="level" defaultValue={course?.level ?? "BEGINNER"}>
                  {LEVELS.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Select>
              </Field>

              <Field label="Bahasa" htmlFor="language" error={errors?.language}>
                <Select id="language" name="language" defaultValue={course?.language ?? "JAVASCRIPT"}>
                  {LANGUAGES.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Select>
              </Field>

              <Field label="Status" htmlFor="status" error={errors?.status}>
                <Select id="status" name="status" defaultValue={course?.status ?? "DRAFT"}>
                  {STATUSES.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Select>
              </Field>
            </div>

            <div className="grid gap-4 sm:grid-cols-2">
              <Field
                label="Estimasi Jam"
                htmlFor="estimatedHours"
                hint="Perkiraan total waktu belajar."
                error={errors?.estimatedHours}
              >
                <Input
                  id="estimatedHours"
                  name="estimatedHours"
                  type="number"
                  min={1}
                  max={400}
                  defaultValue={course?.estimatedHours ?? 8}
                />
              </Field>

              <Field
                label="Kelas"
                htmlFor="classroomId"
                hint="Opsional — kaitkan ke kelas agar siswa otomatis terdaftar."
                error={errors?.classroomId}
              >
                <Select id="classroomId" name="classroomId" defaultValue={course?.classroomId ?? ""}>
                  <option value="">Tanpa kelas</option>
                  {classrooms.map((classroom) => (
                    <option key={classroom.id} value={classroom.id}>
                      {classroom.name}
                    </option>
                  ))}
                </Select>
              </Field>
            </div>

            <Field
              label="Tag"
              htmlFor="tags"
              hint="Pisahkan dengan koma, mis. arduino, sensor, pemula"
              error={errors?.tags}
            >
              <Input id="tags" name="tags" defaultValue={course?.tags.join(", ") ?? ""} />
            </Field>

            <Field label="Warna Sampul" error={errors?.coverColor}>
              <div className="flex flex-wrap gap-2">
                {COLORS.map((option) => (
                  <button
                    key={option}
                    type="button"
                    onClick={() => setColor(option)}
                    aria-label={`Pilih warna ${option}`}
                    aria-pressed={color === option}
                    className={`size-8 rounded-lg border-2 transition-transform hover:scale-105 ${
                      color === option ? "border-primary" : "border-transparent"
                    }`}
                    style={{ backgroundColor: option }}
                  />
                ))}
              </div>
            </Field>
          </DialogBody>

          <DialogFooter>
            <Button type="button" variant="secondary" onClick={() => setOpen(false)}>
              Batal
            </Button>
            <Button type="submit" loading={pending}>
              {mode === "create" ? "Buat Kursus" : "Simpan Perubahan"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
