"use client";

import { useId, useState, useTransition } from "react";
import { Button } from "@/components/ui";
import { inputClass } from "@/components/ui/form";
import { createFormFromTemplateAction } from "@/lib/actions/modules";

/** Copies a form template into a website. Pass `sites` to let a super admin choose the website, or `siteId` for the current one. */
export function FromTemplate({ base, siteId, sites, templates }: { base: string; siteId?: string; sites?: { id: string; name: string }[]; templates: { id: string; name: string; description: string }[] }) {
  const uid = useId();
  const [site, setSite] = useState(siteId ?? sites?.[0]?.id ?? "");
  const [tpl, setTpl] = useState(templates[0]?.id ?? "");
  const [name, setName] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [pending, start] = useTransition();
  if (templates.length === 0) return null;
  const chosen = templates.find((t) => t.id === tpl);
  return (
    <form className="flex flex-wrap items-end gap-2" onSubmit={(e) => { e.preventDefault(); setError(null); start(async () => { const r = await createFormFromTemplateAction(base, site, tpl, name); if (r && !r.ok) setError(r.fieldErrors?.name ?? r.error); }); }}>
      {sites ? <div><label htmlFor={`${uid}-s`} className="mb-1 block text-xs font-medium">Website</label><select id={`${uid}-s`} className={inputClass} value={site} onChange={(e) => setSite(e.target.value)}>{sites.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}</select></div> : null}
      <div><label htmlFor={`${uid}-t`} className="mb-1 block text-xs font-medium">Template</label><select id={`${uid}-t`} className={inputClass} value={tpl} onChange={(e) => setTpl(e.target.value)} aria-describedby={`${uid}-d`}>{templates.map((t) => <option key={t.id} value={t.id}>{t.name}</option>)}</select></div>
      <div><label htmlFor={`${uid}-n`} className="mb-1 block text-xs font-medium">Form name (optional)</label><input id={`${uid}-n`} className={`${inputClass} w-56`} maxLength={120} value={name} placeholder={chosen?.name} onChange={(e) => setName(e.target.value)} /></div>
      <Button type="submit" variant="secondary" disabled={pending || !site || !tpl}>{pending ? "Creating…" : "Add from template"}</Button>
      <p id={`${uid}-d`} className="basis-full text-xs text-muted-foreground">{chosen?.description || "Creates an independent copy you can edit."}</p>
      {error ? <p role="alert" className="basis-full text-xs text-danger">{error}</p> : null}
    </form>
  );
}
