"use client";

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

export interface KnowledgeFormValues {
  id: string;
  topic: string;
  keywords: string[];
  answer: string;
  priority: number;
  published: boolean;
}

const PRIORITIES = [
  { value: "0", label: "Normal" },
  { value: "1", label: "Tinggi" },
  { value: "2", label: "Lebih tinggi" },
  { value: "3", label: "Prioritas utama" },
];

/**
 * Create/edit dialog for one assistant answer.
 *
 * Keywords are entered as free text — one per line — rather than JSON, so the
 * console stays usable for whoever maintains the content.
 */
export function KnowledgeFormDialog({
  mode,
  entry,
  trigger,
  open: controlledOpen,
  onOpenChange,
}: {
  mode: "create" | "edit";
  entry?: KnowledgeFormValues;
  trigger?: React.ReactNode;
  open?: boolean;
  onOpenChange?: (open: boolean) => void;
}) {
  const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false);
  const open = controlledOpen ?? uncontrolledOpen;
  const setOpen = onOpenChange ?? setUncontrolledOpen;

  const action = mode === "create" ? createKnowledgeAction : updateKnowledgeAction;
  const [state, formAction, pending] = useActionState(action, IDLE_ACTION);

  React.useEffect(() => {
    if (state.status === "success") setOpen(false);
  }, [state.status, setOpen]);

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

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      {trigger ? <DialogTrigger asChild>{trigger}</DialogTrigger> : null}

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

          <DialogHeader>
            <DialogTitle>
              {mode === "create" ? "Tambah Pengetahuan" : "Ubah Pengetahuan"}
            </DialogTitle>
            <DialogDescription>
              Jawaban ini dipakai asisten saat pengunjung menanyakan hal yang cocok dengan
              kata kuncinya.
            </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="Topik" htmlFor="topic" required error={errors?.topic}>
              <Input
                id="topic"
                name="topic"
                defaultValue={entry?.topic}
                placeholder="mis. Biaya kursus"
                required
                autoFocus
              />
            </Field>

            <Field
              label="Kata Kunci"
              htmlFor="keywords"
              required
              hint="Satu frasa per baris. Pertanyaan yang memuat salah satunya akan dijawab dengan teks di bawah."
              error={errors?.keywords}
            >
              <Textarea
                id="keywords"
                name="keywords"
                rows={5}
                defaultValue={entry?.keywords.join("\n")}
                placeholder={"biaya\nharga\ntarif\nberapa bayar"}
                required
              />
            </Field>

            <Field
              label="Jawaban"
              htmlFor="answer"
              required
              hint="Tulis lengkap dan ramah. Asisten menampilkan teks ini apa adanya."
              error={errors?.answer}
            >
              <Textarea
                id="answer"
                name="answer"
                rows={7}
                defaultValue={entry?.answer}
                placeholder="Biaya kursus Rp ... per bulan, sudah termasuk ..."
                required
              />
            </Field>

            <div className="grid gap-4 sm:grid-cols-2">
              <Field
                label="Prioritas"
                htmlFor="priority"
                hint="Dipakai saat dua topik berbobot sama."
                error={errors?.priority}
              >
                <Select id="priority" name="priority" defaultValue={String(entry?.priority ?? 0)}>
                  {PRIORITIES.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Select>
              </Field>

              <Field
                label="Status"
                htmlFor="published"
                hint="Nonaktif menyembunyikan jawaban tanpa menghapusnya."
              >
                <Select
                  id="published"
                  name="published"
                  defaultValue={entry ? String(entry.published) : "true"}
                >
                  <option value="true">Aktif</option>
                  <option value="false">Nonaktif</option>
                </Select>
              </Field>
            </div>
          </DialogBody>

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