"use client";

import { useMemo, useRef, useState } from "react";
import { getSupabaseClient } from "@/lib/supabase";

type ImageUploadProps = {
  bucket: string;
  folder?: string;
  value?: string;
  onChange: (url: string) => void;
  aspect?: number;
  ratioLabel?: string;
  hint?: string;
  disabled?: boolean;
  /* Como a miniatura mostra a imagem. Banner corta para preencher, que e o
     padrao; o popup nao corta, e a miniatura precisa contar a mesma historia,
     senao a pessoa aprova aqui uma moldura que nao e a que vai ao ar. */
  encaixe?: "cover" | "contain";
};

function inferExt(file: File) {
  const nameExt = file.name.split(".").pop()?.toLowerCase();
  if (nameExt && /^[a-z0-9]+$/.test(nameExt)) return nameExt;
  const type = (file.type || "").toLowerCase();
  if (type.includes("png")) return "png";
  if (type.includes("webp")) return "webp";
  if (type.includes("jpeg") || type.includes("jpg")) return "jpg";
  return "png";
}

export default function ImageUpload({
  bucket,
  folder,
  value,
  onChange,
  aspect = 32 / 5,
  ratioLabel = "32:5",
  hint = "Recomendado: 2560×400px (32:5). Textos importantes devem ficar centralizados para evitar cortes.",
  disabled,
  encaixe = "cover",
}: ImageUploadProps) {
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const preview = useMemo(() => String(value || "").trim(), [value]);

  async function upload(file: File) {
    setError("");
    setLoading(true);
    try {
      const supabase = getSupabaseClient();
      const ext = inferExt(file);
      const name = `${Math.random().toString(36).slice(2)}_${Date.now()}.${ext}`;
      const path = `${folder ? `${folder.replace(/\/$/, "")}/` : ""}${name}`;
      const { error: uploadError } = await supabase.storage.from(bucket).upload(path, file, {
        upsert: true,
        contentType: file.type || undefined,
      });
      if (uploadError) throw uploadError;

      const { data } = supabase.storage.from(bucket).getPublicUrl(path);
      const publicUrl = data?.publicUrl || "";
      if (!publicUrl) throw new Error("Falha ao gerar URL pública.");
      onChange(publicUrl);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Falha ao enviar imagem.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="space-y-3">
      <div className="flex items-start gap-3">
        <div className="relative overflow-hidden rounded-2xl border border-slate-200 bg-slate-950">
          <div className="w-[260px]" style={{ aspectRatio: `${aspect}` }}>
            {preview ? (
              <img
                src={preview}
                alt="Preview"
                className={`h-full w-full ${encaixe === "contain" ? "object-contain" : "object-cover"}`}
              />
            ) : (
              <div className="flex h-full w-full items-center justify-center bg-[linear-gradient(135deg,rgba(79,70,229,0.18)_0%,rgba(15,23,42,0.72)_55%,rgba(15,23,42,0.88)_100%)]">
                <div className="rounded-full border border-white/15 bg-white/10 px-3 py-1.5 text-xs font-semibold text-white/80">
                  {ratioLabel}
                </div>
              </div>
            )}
          </div>
          {encaixe === "contain" ? null : (
            <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_25%_25%,rgba(0,0,0,0.10)_0%,rgba(0,0,0,0.55)_55%,rgba(0,0,0,0.72)_100%)]" />
          )}
        </div>

        <div className="min-w-0 flex-1 space-y-2">
          <div className="flex flex-wrap items-center gap-2">
            <button
              type="button"
              disabled={disabled || loading}
              onClick={() => inputRef.current?.click()}
              className="inline-flex h-10 items-center justify-center rounded-xl bg-slate-900 px-4 text-sm font-semibold text-white transition hover:bg-slate-800 disabled:opacity-60"
            >
              {loading ? "Enviando..." : preview ? "Trocar imagem" : "Enviar imagem"}
            </button>
            {preview ? (
              <button
                type="button"
                disabled={disabled || loading}
                onClick={() => onChange("")}
                className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-4 text-sm font-semibold text-slate-700 transition hover:bg-slate-50 disabled:opacity-60"
              >
                Remover
              </button>
            ) : null}
          </div>

          <div className="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-600">
            {hint}
          </div>

          {error ? (
            <div className="rounded-xl border border-rose-200 bg-rose-50 px-3 py-2 text-xs font-semibold text-rose-700">
              {error}
            </div>
          ) : null}

          <input
            ref={inputRef}
            type="file"
            accept="image/*"
            className="hidden"
            onChange={(e) => {
              const file = e.target.files?.[0] || null;
              e.target.value = "";
              if (!file) return;
              upload(file);
            }}
          />
        </div>
      </div>
    </div>
  );
}
