"use client";
import { useState, useRef, useCallback } from "react";

export type BlazeImgUploadResult = {
  url: string;
  key: string;
  size: number;
  type: string;
};

export type BlazeImgUploaderProps = {
  apiKey?: string;
  baseUrl?: string;
  folder?: string;
  visibility?: "public" | "private";
  accept?: string;
  multiple?: boolean;
  onUpload?: (result: BlazeImgUploadResult) => void;
  onError?: (error: string) => void;
  className?: string;
  children?: React.ReactNode;
};

export function BlazeImgUploader({
  apiKey,
  baseUrl = "",
  folder,
  visibility = "public",
  accept = "image/*,video/*",
  multiple = false,
  onUpload,
  onError,
  className,
  children,
}: BlazeImgUploaderProps) {
  const [uploading, setUploading] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  const handleFiles = useCallback(
    async (files: FileList | File[]) => {
      const arr = Array.from(files);
      if (!arr.length) return;
      setUploading(true);
      try {
        for (const file of arr) {
          const form = new FormData();
          form.append("file", file);
          if (folder) form.append("folder", folder);
          if (visibility) form.append("visibility", visibility);
          const headers: Record<string, string> = {};
          if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
          const res = await fetch(`${baseUrl}/api/upload`, { method: "POST", body: form, headers });
          const data = await res.json();
          if (!res.ok) throw new Error(data.error || "Upload failed");
          const result: BlazeImgUploadResult = { url: data.url, key: data.key, size: data.size, type: data.type };
          onUpload?.(result);
        }
      } catch (e) {
        onError?.(e instanceof Error ? e.message : "Upload failed");
      } finally {
        setUploading(false);
      }
    },
    [apiKey, baseUrl, folder, visibility, onUpload, onError]
  );

  return (
    <div className={className}>
      <input
        ref={inputRef}
        type="file"
        accept={accept}
        multiple={multiple}
        className="hidden"
        onChange={(e) => e.target.files && handleFiles(e.target.files)}
        disabled={uploading}
      />
      <button type="button" onClick={() => inputRef.current?.click()} disabled={uploading}>
        {children || (uploading ? "Uploading…" : "Upload")}
      </button>
    </div>
  );
}