import React, { useRef, useState } from "react";
import { DashboardTemplatePage } from "./DashboardTemplatePage";
import { COLORS, btnBase, chip } from "./ui-tokens";

type FormState = {
  id: string;               // kebab-case
  name: string;             // display
  category: string;
  tags: string;
  sections: string;         // one per line (optional)
};

export default function AdminUploadBusinessPlanTemplate() {
  const [form, setForm] = useState<FormState>({
    id: "",
    name: "",
    category: "",
    tags: "",
    sections: "Executive Summary\nMarket Analysis\nProducts & Services\nMarketing & Sales\nOperations Plan\nOrganization & Management\nFinancial Plan\nAppendices"
  });

  const [docxFile, setDocxFile] = useState<File | null>(null);
  const [previewFile, setPreviewFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string>("");

  const [msg, setMsg] = useState<string>("");
  const [busy, setBusy] = useState(false);

  const docRef = useRef<HTMLInputElement>(null);
  const prevRef = useRef<HTMLInputElement>(null);

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setMsg("");
    if (!/^[a-z0-9\-]+$/.test(form.id)) return setMsg("ID must be kebab-case (letters/numbers/dashes).");
    if (!form.name) return setMsg("Name is required.");
    if (!docxFile) return setMsg("DOCX file is required.");
    if (!previewFile) return setMsg("Preview image is required.");

    try {
      setBusy(true);
      const fd = new FormData();
      fd.append("id", form.id);
      fd.append("name", form.name);
      fd.append("category", form.category);
      fd.append("tags", form.tags);
      fd.append("sections", form.sections);
      fd.append("docx", docxFile);
      fd.append("preview", previewFile);

      const res = await fetch("/api/bp-templates/upload", { method: "POST", body: fd });
      const json = await res.json().catch(()=>({}));
      if (!res.ok) throw new Error(json?.error || `HTTP ${res.status}`);
      setMsg("Uploaded and manifest updated ✅");
    } catch (e: any) {
      setMsg("Upload failed: " + (e?.message || "Unknown error"));
    } finally {
      setBusy(false);
    }
  };

  return (
    <DashboardTemplatePage title="Upload Business Plan Template">
      <form className="grid md:grid-cols-2 gap-6" onSubmit={onSubmit}>
        <section className="space-y-4">
          <Field label="Template ID" hint="kebab-case, e.g. barber-shop">
            <input className="rounded-lg border px-3 py-2 w-full"
              value={form.id} onChange={e=>setForm(s=>({...s, id:e.target.value}))}/>
          </Field>
          <Field label="Display Name">
            <input className="rounded-lg border px-3 py-2 w-full"
              value={form.name} onChange={e=>setForm(s=>({...s, name:e.target.value}))}/>
          </Field>
          <Field label="Category">
            <input className="rounded-lg border px-3 py-2 w-full"
              value={form.category} onChange={e=>setForm(s=>({...s, category:e.target.value}))}/>
          </Field>
          <Field label="Tags (comma-separated)">
            <input className="rounded-lg border px-3 py-2 w-full"
              value={form.tags} onChange={e=>setForm(s=>({...s, tags:e.target.value}))}/>
            <div className="mt-1 flex flex-wrap gap-1">
              {form.tags.split(",").map(t => t.trim()).filter(Boolean).map(t => <span key={t} className={chip}>{t}</span>)}
            </div>
          </Field>
          <Field label="Sections (optional, one per line)">
            <textarea className="rounded-lg border px-3 py-2 w-full h-40"
              value={form.sections} onChange={e=>setForm(s=>({...s, sections:e.target.value}))}/>
          </Field>
        </section>

        <section className="space-y-4">
          <FilePick label="Template File (DOCX)" accept=".docx"
            file={docxFile} onClick={()=>docRef.current?.click()} onClear={()=>setDocxFile(null)} />
          <input ref={docRef} type="file" accept=".docx" className="hidden"
            onChange={(e)=>setDocxFile(e.target.files?.[0] || null)} />

          <FilePick label="Preview (PNG/JPG)" accept=".png,.jpg,.jpeg"
            file={previewFile} onClick={()=>prevRef.current?.click()} onClear={()=>{
              setPreviewFile(null); setPreviewUrl("");
            }} />
          <input ref={prevRef} type="file" accept=".png,.jpg,.jpeg" className="hidden"
            onChange={(e)=>{
              const f = e.target.files?.[0] || null;
              setPreviewFile(f);
              if (f) {
                const r = new FileReader();
                r.onload = () => setPreviewUrl(String(r.result || ""));
                r.readAsDataURL(f);
              } else setPreviewUrl("");
            }} />

          <div className="rounded-xl border p-3 bg-white">
            <div className="text-xs text-gray-600 mb-2">Preview</div>
            <div className="aspect-video rounded-lg bg-gray-50 overflow-hidden flex items-center justify-center">
              {previewUrl ? <img src={previewUrl} className="object-contain w-full h-full"/> : <div className="text-gray-400">No preview selected</div>}
            </div>
          </div>

          <div className="pt-1">
            <button className={btnBase} style={{ backgroundColor: COLORS.green, color: COLORS.white }} disabled={busy} type="submit">
              {busy ? "Uploading…" : "Upload & Update Manifest"}
            </button>
          </div>

          {msg && <p className="text-sm text-gray-600">{msg}</p>}
        </section>
      </form>
    </DashboardTemplatePage>
  );
}

function Field({label, hint, children}:{label:string; hint?:string; children:React.ReactNode}) {
  return (
    <div className="grid gap-1">
      <label className="text-xs text-gray-600">{label}</label>
      {children}
      {hint && <div className="text-[11px] text-gray-400">{hint}</div>}
    </div>
  );
}

function FilePick({label, accept, file, onClick, onClear}:{label:string; accept:string; file:File|null; onClick:()=>void; onClear:()=>void;}) {
  return (
    <div className="grid gap-1">
      <label className="text-xs text-gray-600">{label}</label>
      <div
        className="rounded-xl border-dashed border-2 p-4 text-sm text-gray-600 flex items-center justify-between gap-3 cursor-pointer"
        onClick={onClick}
        title="Click to choose a file"
      >
        <div className="flex-1">
          {file ? <span className="font-medium">{file.name}</span> : <>Click to select</>}
          <div className="text-[11px] text-gray-400">Accepted: {accept}</div>
        </div>
        <div className="flex items-center gap-2">
          <button type="button" className={btnBase} style={{ backgroundColor: COLORS.green, color: COLORS.white }} onClick={onClick}>Choose</button>
          {file && <button type="button" className={btnBase} style={{ backgroundColor: COLORS.darkGray, color: COLORS.white }} onClick={onClear}>Remove</button>}
        </div>
      </div>
    </div>
  );
}
