import React, { useRef, useState } from "react";
import { DashboardTemplatePage } from "./DashboardTemplatePage";

type FormState = {
  id: string;
  name: string;
  brandName: string;
  tagline: string;
  estYear: string;
  primary: string;
  secondary: string;
  accent: string;
  tags: string;
};

export default function AdminUploadLogoTemplate() {
  const [svgFile, setSvgFile] = useState<File | null>(null);
  const [previewFile, setPreviewFile] = useState<File | null>(null);
  const [msg, setMsg] = useState<string>("");
  const [busy, setBusy] = useState(false);

  const [form, setForm] = useState<FormState>({
    id: "",
    name: "",
    brandName: "Your Brand",
    tagline: "Your Tagline",
    estYear: "2025",
    primary: "#231f20",
    secondary: "#978752",
    accent: "#6dc282",
    tags: "modern, emblem",
  });

  const svgInputRef = useRef<HTMLInputElement>(null);
  const previewInputRef = useRef<HTMLInputElement>(null);

  const handleDrop = (e: React.DragEvent<HTMLDivElement>, kind: "svg"|"preview") => {
    e.preventDefault();
    const f = e.dataTransfer.files?.[0];
    if (!f) return;
    if (kind === "svg" && f.type !== "image/svg+xml") {
      return setMsg("SVG drop rejected: not an SVG file.");
    }
    if (kind === "preview" && !/^image\/(png|jpeg)$/.test(f.type)) {
      return setMsg("Preview must be PNG or JPG.");
    }
    kind === "svg" ? setSvgFile(f) : setPreviewFile(f);
  };

  const readText = (file: File) => new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.onerror = () => reject(new Error("Failed to read file"));
    reader.onload = () => resolve(String(reader.result || ""));
    reader.readAsText(file);
  });

  const validateSVG = async (file: File) => {
    if (!file) return "Please provide an SVG file.";
    if (file.type !== "image/svg+xml") return "File is not an SVG.";
    const text = await readText(file);
    const issues: string[] = [];
    if (!/^\s*<svg[\s\S]*<\/svg>\s*$/i.test(text)) issues.push("Not a valid <svg>…</svg> document.");
    ["{Brand_Name}", "{Tagline}", "{Est_Year}"].forEach(tok => {
      if (!text.includes(tok)) issues.push(`Missing token ${tok}`);
    });
    ["--primary","--secondary","--accent"].forEach(v => {
      if (!text.includes(v)) issues.push(`Missing CSS var ${v}`);
    });
    return issues.length ? issues.join(" ") : null;
  };

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setMsg("");
    if (!form.id || !form.name) return setMsg("ID and Name are required.");
    if (!svgFile || !previewFile) return setMsg("SVG and Preview files are required.");
    const svgErr = await validateSVG(svgFile);
    if (svgErr) return setMsg("SVG validation failed: " + svgErr);

    try {
      setBusy(true);
      const fd = new FormData();
      fd.append("id", form.id);
      fd.append("name", form.name);
      fd.append("brandName", form.brandName);
      fd.append("tagline", form.tagline);
      fd.append("estYear", form.estYear);
      fd.append("primary", form.primary);
      fd.append("secondary", form.secondary);
      fd.append("accent", form.accent);
      fd.append("tags", form.tags);
      fd.append("svg", svgFile);
      fd.append("preview", previewFile);

      const res = await fetch("/api/logo-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 ✅");
      // reset optional
      // setSvgFile(null); setPreviewFile(null);
    } catch (e: any) {
      setMsg("Upload failed: " + (e?.message || "Unknown error"));
    } finally {
      setBusy(false);
    }
  };

  return (
    <DashboardTemplatePage title="Upload Logo 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. logo-emblem-law-v1">
            <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>

          <div className="grid grid-cols-3 gap-4">
            <Field label="Primary"><input type="color" className="h-10 w-full rounded border" value={form.primary} onChange={e=>setForm(s=>({...s, primary:e.target.value}))}/></Field>
            <Field label="Secondary"><input type="color" className="h-10 w-full rounded border" value={form.secondary} onChange={e=>setForm(s=>({...s, secondary:e.target.value}))}/></Field>
            <Field label="Accent"><input type="color" className="h-10 w-full rounded border" value={form.accent} onChange={e=>setForm(s=>({...s, accent:e.target.value}))}/></Field>
          </div>

          <Field label="Default Brand_Name">
            <input className="rounded-lg border px-3 py-2 w-full"
              value={form.brandName} onChange={e=>setForm(s=>({...s, brandName:e.target.value}))}/>
          </Field>
          <Field label="Default Tagline">
            <input className="rounded-lg border px-3 py-2 w-full"
              value={form.tagline} onChange={e=>setForm(s=>({...s, tagline:e.target.value}))}/>
          </Field>
          <Field label="Default Est_Year">
            <input className="rounded-lg border px-3 py-2 w-full"
              value={form.estYear} onChange={e=>setForm(s=>({...s, estYear: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}))}/>
          </Field>
        </section>

        <section className="space-y-4">
          <FileDrop
            label="SVG Master"
            accept=".svg"
            file={svgFile}
            onRemove={()=>setSvgFile(null)}
            onClick={()=>svgInputRef.current?.click()}
            onDrop={(e)=>handleDrop(e,"svg")}
          />
          <input ref={svgInputRef} type="file" accept=".svg" className="hidden"
            onChange={(e)=>setSvgFile(e.target.files?.[0] || null)} />

          <FileDrop
            label="Preview (PNG/JPG)"
            accept=".png,.jpg,.jpeg"
            file={previewFile}
            onRemove={()=>setPreviewFile(null)}
            onClick={()=>previewInputRef.current?.click()}
            onDrop={(e)=>handleDrop(e,"preview")}
          />
          <input ref={previewInputRef} type="file" accept=".png,.jpg,.jpeg" className="hidden"
            onChange={(e)=>setPreviewFile(e.target.files?.[0] || null)} />

          <div className="pt-2">
            <button className="rounded-xl px-4 py-2 border hover:bg-gray-50" disabled={busy} type="submit">
              {busy ? "Uploading…" : "Upload & Update Manifest"}
            </button>
          </div>

          {msg && <p className="text-sm text-gray-600">{msg}</p>}

          <p className="text-xs text-gray-500">
            SVG must contain tokens <code>{`{Brand_Name}`}</code>, <code>{`{Tagline}`}</code>, <code>{`{Est_Year}`}</code> and CSS vars <code>--primary</code>, <code>--secondary</code>, <code>--accent</code>.
          </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 FileDrop({
  label, accept, file, onRemove, onClick, onDrop
}:{
  label:string; accept:string; file:File|null;
  onRemove:()=>void; onClick:()=>void; onDrop:(e:React.DragEvent<HTMLDivElement>)=>void;
}) {
  return (
    <div>
      <label className="text-xs text-gray-600">{label}</label>
      <div
        onDragOver={(e)=>e.preventDefault()}
        onDrop={onDrop}
        className="mt-1 rounded-xl border-dashed border-2 p-4 text-sm text-gray-600 flex items-center justify-between gap-3"
      >
        <div className="flex-1">
          {file ? <span className="font-medium">{file.name}</span> : <>Drag & drop, or 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="rounded-lg px-3 py-1 border" onClick={onClick}>Choose</button>
          {file && <button type="button" className="rounded-lg px-3 py-1 border" onClick={onRemove}>Remove</button>}
        </div>
      </div>
    </div>
  );
}
