"use client";
import { useMemo, useState } from "react";
import { Plus, Trash2 } from "lucide-react";
import { buildFrontmatter, type PropField, type PropType } from "@/lib/tools/frontmatter";
import { CodeOutput } from "@/components/tools/CodeOutput";

const TYPES: PropType[] = ["text", "number", "checkbox", "date", "list", "tags"];
const TYPE_RU: Record<PropType, string> = {
  text: "текст", number: "число", checkbox: "флажок", date: "дата", list: "список", tags: "теги",
};

const field = "w-full p-2 text-sm";
const fieldStyle = { border: "1px solid var(--border)", borderRadius: "2px", backgroundColor: "var(--background)", color: "var(--foreground)" } as const;

export function FrontmatterForm() {
  const [fields, setFields] = useState<PropField[]>([
    { key: "title", type: "text", value: "Моя заметка" },
    { key: "tags", type: "tags", value: "obsidian, pkm" },
    { key: "created", type: "date", value: "2026-06-23" },
  ]);

  const yaml = useMemo(() => buildFrontmatter(fields), [fields]);

  function update(i: number, patch: Partial<PropField>) {
    setFields((prev) => prev.map((f, idx) => (idx === i ? { ...f, ...patch } : f)));
  }
  function addRow() {
    setFields((prev) => [...prev, { key: "", type: "text", value: "" }]);
  }
  function removeRow(i: number) {
    setFields((prev) => prev.filter((_, idx) => idx !== i));
  }

  return (
    <div className="grid gap-6 md:grid-cols-2">
      <div className="flex flex-col gap-3">
        {fields.map((f, i) => (
          <div key={i} className="flex flex-col gap-2 p-2" style={{ border: "1px solid var(--border)", borderRadius: "2px" }}>
            <div className="flex items-center gap-2">
              <input
                className={field} style={fieldStyle} placeholder="имя свойства"
                value={f.key} onChange={(e) => update(i, { key: e.target.value })}
              />
              <button
                type="button" onClick={() => removeRow(i)} aria-label="Удалить свойство"
                className="btn-aubade inline-flex items-center justify-center p-2"
              >
                <Trash2 size={16} />
              </button>
            </div>
            <div className="flex items-center gap-2">
              <select
                className={field} style={fieldStyle}
                value={f.type} onChange={(e) => update(i, { type: e.target.value as PropType })}
              >
                {TYPES.map((t) => <option key={t} value={t}>{TYPE_RU[t]}</option>)}
              </select>
              {f.type === "checkbox" ? (
                <select className={field} style={fieldStyle} value={f.value ?? "false"} onChange={(e) => update(i, { value: e.target.value })}>
                  <option value="true">true</option>
                  <option value="false">false</option>
                </select>
              ) : f.type === "date" ? (
                <input
                  type="date" className={field} style={fieldStyle}
                  value={f.value ?? ""} onChange={(e) => update(i, { value: e.target.value })}
                />
              ) : (
                <input
                  className={field} style={fieldStyle}
                  placeholder={f.type === "list" || f.type === "tags" ? "через запятую" : "значение"}
                  value={f.value ?? ""} onChange={(e) => update(i, { value: e.target.value })}
                />
              )}
            </div>
          </div>
        ))}
        <button type="button" onClick={addRow} className="btn-aubade inline-flex items-center justify-center gap-2 text-sm">
          <Plus size={16} /> Добавить свойство
        </button>
      </div>
      <div className="flex flex-col gap-4">
        <CodeOutput code={yaml} tool="frontmatter" label="YAML-frontmatter" />
      </div>
    </div>
  );
}
