"use client";

import { useRef, useState } from "react";

/**
 * Drop-in "📎 Add image" button for any composer textarea. Wires
 * straight to the shared /api/upload/image pipeline (#62) so every
 * upload across the site is optimized the same way.
 *
 * On successful upload, the markdown `![alt](primaryUrl)` is appended
 * to the textarea via the onInsert callback — bodies stay markdown so
 * server-side rendering can swap to <picture> with AVIF on read.
 *
 * Props:
 *   onInsert(markdown) — called with the markdown to append
 *   disabled?         — optional manual disable
 *   maxBytes?         — client-side guard (default 20 MB)
 */
interface Props {
  onInsert: (markdown: string) => void;
  disabled?: boolean;
  maxBytes?: number;
}

export default function ImageAttachButton({ onInsert, disabled, maxBytes = 20 * 1024 * 1024 }: Props) {
  const fileRef = useRef<HTMLInputElement | null>(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  async function handleFile(file: File) {
    setErr(null);
    if (file.size > maxBytes) {
      setErr(`Too large (${(file.size / 1024 / 1024).toFixed(1)} MB). Max 20 MB.`);
      return;
    }
    if (!file.type.startsWith("image/")) {
      setErr("Not an image file.");
      return;
    }
    setBusy(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      const r = await fetch("/api/upload/image", { method: "POST", body: fd });
      const j = await r.json().catch(() => ({}));
      if (!r.ok) {
        setErr(j.error || `Upload failed (${r.status})`);
      } else if (j.primaryUrl) {
        const alt = file.name.replace(/\.[^.]+$/, "");
        onInsert(`\n\n![${alt}](${j.primaryUrl})\n\n`);
      } else {
        setErr("Upload succeeded but no URL returned.");
      }
    } catch (e: unknown) {
      setErr(e instanceof Error ? e.message : "Upload failed");
    } finally {
      setBusy(false);
      if (fileRef.current) fileRef.current.value = "";
    }
  }

  return (
    <div className="inline-flex flex-col">
      <div className="inline-flex items-center gap-2">
        <button
          type="button"
          onClick={() => fileRef.current?.click()}
          disabled={busy || disabled}
          className="inline-flex items-center gap-1.5 bg-[#DCE6F2] hover:bg-[#333] disabled:opacity-50 text-[#aaa] font-body text-xs px-3 py-1.5 rounded-md transition-colors border border-[#333]"
          title="Attach an image (auto-optimized, max 20 MB)"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
            <path d="M21.44 11.05l-9.19 9.19a6 6 0 1 1-8.49-8.49l9.19-9.19a4 4 0 1 1 5.66 5.66l-9.2 9.19a2 2 0 1 1-2.83-2.83l8.49-8.48" />
          </svg>
          {busy ? "Uploading…" : "Attach image"}
        </button>
        <input
          ref={fileRef}
          type="file"
          accept="image/jpeg,image/png,image/webp,image/gif,image/avif"
          className="hidden"
          onChange={(e) => {
            const f = e.target.files?.[0];
            if (f) void handleFile(f);
          }}
        />
      </div>
      {err && <div className="text-[11px] text-red-400 mt-1">{err}</div>}
    </div>
  );
}
