"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import type { ProductContent } from "@/lib/product-types";

type Props = {
  productSlug: string;
};

export default function ProductContentManager({ productSlug }: Props) {
  const [items, setItems] = useState<ProductContent[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploadingId, setUploadingId] = useState<string | null>(null);
  const [err, setErr] = useState("");
  const fileRefs = useRef<Record<string, HTMLInputElement | null>>({});

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/products/${productSlug}/contents`, { credentials: "include" });
      const data = await res.json();
      setItems(data.items || []);
    } catch {
      setItems([]);
    } finally {
      setLoading(false);
    }
  }, [productSlug]);

  useEffect(() => {
    load();
  }, [load]);

  async function addContent(type: "ebook" | "video") {
    setErr("");
    const res = await fetch(`/api/products/${productSlug}/contents`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ type }),
    });
    const data = await res.json();
    if (!res.ok) {
      setErr(data.error || "Erro ao adicionar");
      return;
    }
    setItems((prev) => [...prev, data.item]);
  }

  async function uploadFile(contentId: string, file: File) {
    setUploadingId(contentId);
    setErr("");
    try {
      const fd = new FormData();
      fd.append("file", file);
      fd.append("slug", productSlug);
      fd.append("contentId", contentId);
      const res = await fetch("/api/uploads/content", { method: "POST", body: fd, credentials: "include" });
      const raw = await res.text();
      let data: { item?: ProductContent; error?: string };
      try {
        data = JSON.parse(raw);
      } catch {
        throw new Error(res.ok ? "Resposta inválida" : `Upload falhou (${res.status})`);
      }
      if (!res.ok) throw new Error(data.error || "Falha no upload");
      setItems((prev) => prev.map((i) => (i.id === contentId ? data.item! : i)));
    } catch (e) {
      setErr(e instanceof Error ? e.message : "Erro no upload");
    } finally {
      setUploadingId(null);
    }
  }

  async function removeContent(id: string) {
    if (!confirm("Remover este conteúdo?")) return;
    const res = await fetch(`/api/products/${productSlug}/contents/${id}`, {
      method: "DELETE",
      credentials: "include",
    });
    if (res.ok) setItems((prev) => prev.filter((i) => i.id !== id));
  }

  async function renameContent(id: string, title: string) {
    await fetch(`/api/products/${productSlug}/contents/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ title }),
    });
    setItems((prev) => prev.map((i) => (i.id === id ? { ...i, title } : i)));
  }

  if (loading) {
    return <p style={{ fontSize: ".82rem", color: "rgba(255,255,255,.5)" }}>Carregando conteúdos…</p>;
  }

  return (
    <div className="content-mgr">
      {items.length === 0 ? (
        <p style={{ fontSize: ".85rem", color: "rgba(255,255,255,.55)", marginBottom: 12 }}>
          Nenhum conteúdo — adicione PDFs ou vídeos para o comprador.
        </p>
      ) : null}

      {items.map((item, idx) => (
        <div className="content-row" key={item.id}>
          <div className="content-row-top">
            <span className="content-type">{item.type === "video" ? "🎬" : "📄"}</span>
            <input
              className="content-title-input"
              value={item.title}
              onChange={(e) => renameContent(item.id, e.target.value)}
              placeholder={item.type === "video" ? "Título do vídeo" : "Título do e-book"}
            />
            <button type="button" className="content-del" onClick={() => removeContent(item.id)} title="Remover">
              ×
            </button>
          </div>
          <p style={{ fontSize: ".75rem", color: item.filePath ? "#c8f135" : "rgba(255,255,255,.45)", margin: "6px 0" }}>
            {item.filePath
              ? `✓ ${item.filePath.split("/").pop()}`
              : item.type === "video"
                ? "Envie MP4, WebM ou MOV"
                : "Envie um PDF"}
          </p>
          <button
            type="button"
            disabled={uploadingId === item.id}
            onClick={() => fileRefs.current[item.id]?.click()}
            style={{
              width: "100%",
              padding: "8px 10px",
              background: "rgba(255,255,255,.08)",
              border: "1px solid rgba(255,255,255,.15)",
              borderRadius: 8,
              color: "#fff",
              cursor: uploadingId === item.id ? "wait" : "pointer",
              fontSize: ".8rem",
            }}
          >
            {uploadingId === item.id ? "Enviando…" : item.filePath ? "Substituir arquivo" : "Enviar arquivo"}
          </button>
          <input
            ref={(el) => {
              fileRefs.current[item.id] = el;
            }}
            type="file"
            hidden
            accept={item.type === "video" ? "video/mp4,video/webm,video/quicktime,.mp4,.webm,.mov" : "application/pdf,.pdf"}
            onChange={(e) => {
              const f = e.target.files?.[0];
              if (f) uploadFile(item.id, f);
              e.target.value = "";
            }}
          />
          {idx < items.length - 1 ? <hr style={{ border: 0, borderTop: "1px solid rgba(255,255,255,.08)", margin: "12px 0" }} /> : null}
        </div>
      ))}

      <div className="content-add-row">
        <button type="button" className="content-add-btn" onClick={() => addContent("ebook")}>
          + PDF
        </button>
        <button type="button" className="content-add-btn" onClick={() => addContent("video")}>
          + Vídeo
        </button>
      </div>

      {err ? <p style={{ color: "#f87171", fontSize: ".78rem", marginTop: 8 }}>{err}</p> : null}
    </div>
  );
}
