"use client";

import { useRef, useState } from "react";

type Props = {
  productSlug: string;
  ebookFile: string | null;
  onUploaded: (path: string) => void;
};

export default function EbookUploadField({ productSlug, ebookFile, onUploaded }: Props) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [err, setErr] = useState("");

  const fileName = ebookFile?.split("/").pop() || null;

  async function onFile(file: File | null) {
    if (!file) return;
    setUploading(true);
    setErr("");
    try {
      const fd = new FormData();
      fd.append("file", file);
      fd.append("slug", productSlug);
      const res = await fetch("/api/uploads/ebook", { method: "POST", body: fd, credentials: "include" });
      const raw = await res.text();
      let data: { path?: string; error?: string };
      try {
        data = JSON.parse(raw) as { path?: string; error?: string };
      } catch {
        throw new Error(
          res.ok ? "Resposta inválida do servidor" : `Upload falhou (${res.status}). Tente de novo.`
        );
      }
      if (!res.ok) throw new Error(data.error || "Falha no upload");
      if (!data.path) throw new Error("Resposta sem caminho do arquivo");
      onUploaded(data.path);
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Erro no upload");
    } finally {
      setUploading(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  }

  return (
    <div>
      {fileName ? (
        <p style={{ fontSize: ".85rem", color: "#c8f135", marginBottom: 10 }}>
          ✓ PDF anexado: <b>{fileName}</b>
        </p>
      ) : (
        <p style={{ fontSize: ".85rem", color: "rgba(255,255,255,.55)", marginBottom: 10 }}>
          Nenhum e-book enviado — o comprador não conseguirá baixar após o pagamento.
        </p>
      )}
      <button
        type="button"
        disabled={uploading}
        onClick={() => inputRef.current?.click()}
        style={{
          width: "100%",
          padding: "10px 12px",
          background: "rgba(255,255,255,.08)",
          border: "1px solid rgba(255,255,255,.15)",
          borderRadius: 8,
          color: "#fff",
          cursor: uploading ? "wait" : "pointer",
          fontFamily: "var(--fb)",
          fontSize: ".82rem",
        }}
      >
        {uploading ? "Enviando PDF…" : fileName ? "📤 Substituir PDF" : "📤 Enviar PDF do e-book"}
      </button>
      <input
        ref={inputRef}
        type="file"
        accept="application/pdf,.pdf"
        hidden
        onChange={(e) => onFile(e.target.files?.[0] ?? null)}
      />
      {err ? <p style={{ color: "#f87171", fontSize: ".78rem", marginTop: 8 }}>{err}</p> : null}
      <p style={{ fontSize: ".72rem", color: "rgba(255,255,255,.45)", marginTop: 8 }}>
        Apenas PDF • máx. 30 MB • liberado na biblioteca do comprador após pagamento
      </p>
    </div>
  );
}
