"use client";

import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";

type Props = {
    onUploaded: () => void;
    multiple?: boolean;
    accept?: string; // مثل "image/*"
};

export function MediaUploader({ onUploaded, multiple = false, accept }: Props) {
    const inputRef = useRef<HTMLInputElement | null>(null);
    const [loading, setLoading] = useState(false);

    async function uploadFile(file: File) {
        setLoading(true);
        try {
            const fd = new FormData();
            fd.append("file", file);

            const res = await fetch("/api/media/upload", {
                method: "POST",
                body: fd,
            });

            const json = await res.json();
            if (!json.ok) throw new Error(json.error || "Upload failed");

            toast.success("فایل آپلود شد");
            onUploaded();
        } catch (e: any) {
            toast.error(e?.message ?? "خطا در آپلود");
        } finally {
            setLoading(false);
        }
    }

    async function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
        const files = e.target.files ? Array.from(e.target.files) : [];
        if (!files.length) return;

        // فعلاً آپلود تکی (طبق API فعلی). اگر multiple خواستی، بعداً batch می‌کنیم.
        await uploadFile(files[0]);

        // reset تا اگر همون فایل دوباره انتخاب شد دوباره onChange بخوره
        e.target.value = "";
    }

    return (
        <div className="flex items-center gap-2">
            <input
                ref={inputRef}
                type="file"
                className="hidden"
                multiple={multiple}
                accept={accept}
                onChange={handleChange}
            />

            <Button
                type="button"
                variant="outline"
                disabled={loading}
                onClick={() => inputRef.current?.click()}
            >
                {loading ? "در حال آپلود..." : "آپلود فایل"}
            </Button>
        </div>
    );
}
