"use client";

import { useRef, useState } from "react";
import { assetDisplayUrl } from "@/lib/asset-url";

type Props = {
  url: string;
  onUrl: (url: string) => void;
  scale?: number;
  onScale?: (scale: number) => void;
  showScale?: boolean;
  previewHeight?: number;
};

export default function ImageUploadField({
  url,
  onUrl,
  scale = 100,
  onScale,
  showScale = false,
  previewHeight = 72,
}: Props) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [err, setErr] = useState("");

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

  const previewSrc = assetDisplayUrl(url);

  return (
    <div>
      <span>Enviar do computador</span>
      <div style={{ marginTop: 6 }}>
        <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…" : "📤 Escolher arquivo"}
        </button>
        <input
          ref={inputRef}
          type="file"
          accept="image/jpeg,image/png,image/webp,image/gif"
          hidden
          onChange={(e) => onFile(e.target.files?.[0] ?? null)}
        />
      </div>
      {err ? <p style={{ color: "#f87171", fontSize: ".78rem", marginTop: 8 }}>{err}</p> : null}
      <p style={{ fontSize: ".72rem", color: "rgba(255,255,255,.45)", marginTop: 8 }}>
        JPG, PNG, WebP ou GIF • máx. 5 MB • permanece após deploy
      </p>

      <span style={{ display: "block", marginTop: 12 }}>Ou cole uma URL</span>
      <input
        className="lped-input"
        value={url}
        onChange={(e) => onUrl(e.target.value)}
        placeholder="/uploads/arquivo.webp ou https://..."
        style={{
          width: "100%",
          marginTop: 6,
          background: "rgba(255,255,255,.05)",
          border: "1px solid rgba(255,255,255,.12)",
          borderRadius: 9,
          color: "#fff",
          padding: "10px 11px",
          fontFamily: "var(--fb)",
          fontSize: ".9rem",
        }}
      />

      {showScale && onScale ? (
        <div style={{ marginTop: 16 }}>
          <span>
            Tamanho: <b>{scale}%</b>
          </span>
          <input
            type="range"
            min={50}
            max={200}
            step={5}
            value={scale}
            onChange={(e) => onScale(Number(e.target.value))}
            style={{ width: "100%", marginTop: 8, accentColor: "#c8f135" }}
          />
        </div>
      ) : null}

      {previewSrc ? (
        <div
          style={{
            marginTop: 12,
            height: previewHeight,
            borderRadius: 9,
            overflow: "hidden",
            background: `center/cover no-repeat url("${previewSrc.replace(/"/g, "%22")}")`,
          }}
        />
      ) : null}
    </div>
  );
}
