"use client";

import { Button } from "@/components/ui/Button";
import { Field, Input, Select, Textarea } from "@/components/ui/Field";
import { FormFieldDraft, DEFAULT_FIELD } from "@/lib/rule-set";

export function FormFieldListEditor({
  items,
  onChange,
}: {
  items: FormFieldDraft[];
  onChange: (items: FormFieldDraft[]) => void;
}) {
  const update = (index: number, patch: Partial<FormFieldDraft>) => {
    onChange(items.map((item, i) => (i === index ? { ...item, ...patch } : item)));
  };

  const remove = (index: number) => {
    onChange(items.filter((_, i) => i !== index));
  };

  const add = () => onChange([...items, { ...DEFAULT_FIELD }]);

  return (
    <div className="space-y-3">
      {items.map((field, index) => (
        <div key={index} className="rounded-xl border border-[var(--border)] bg-slate-50 p-3">
          <div className="grid gap-3">
            <Field label="عنوان سوال">
              <Input
                value={field.label}
                placeholder="مثلاً: نام مدرسه قبلی"
                onChange={(e) => update(index, { label: e.target.value })}
              />
            </Field>
            <Field label="نوع پاسخ">
              <Select
                value={field.type}
                onChange={(e) =>
                  update(index, { type: e.target.value as FormFieldDraft["type"] })
                }
              >
                <option value="text">متن کوتاه</option>
                <option value="textarea">متن بلند</option>
                <option value="number">عدد</option>
                <option value="select">انتخاب از لیست</option>
                <option value="date">تاریخ</option>
              </Select>
            </Field>
            {field.type === "select" ? (
              <Field
                label="گزینه‌های لیست"
                hint="هر خط یک گزینه — همان متنی که اولیا می‌بینند"
              >
                <Textarea
                  rows={4}
                  value={field.options}
                  placeholder={"ندارد\nورزشی\nعلمی"}
                  onChange={(e) => update(index, { options: e.target.value })}
                />
              </Field>
            ) : null}
            <label className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                checked={field.required}
                onChange={(e) => update(index, { required: e.target.checked })}
              />
              پاسخ اجباری باشد
            </label>
          </div>
          {items.length > 1 ? (
            <button type="button" onClick={() => remove(index)} className="mt-2 text-xs text-red-600">
              حذف سوال
            </button>
          ) : null}
        </div>
      ))}
      <Button type="button" variant="secondary" onClick={add}>
        + افزودن سوال
      </Button>
    </div>
  );
}
