import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { Upload } from "lucide-react";
import * as React from "react";
import { cn } from "../../lib/utils";
import { Button } from "./button";
function UploadButton({ className, variant = "default", size = "default", accept = "*/*", multiple = false, onFileSelect, onUpload, uploadUrl, disabled = false, children, auto = false, ...props }) {
    const fileInputRef = React.useRef(null);
    const handleButtonClick = () => {
        fileInputRef.current?.click();
    };
    const handleFileChange = async (event) => {
        const files = event.target.files;
        if (!files || files.length === 0)
            return;
        onFileSelect?.(files);
        if (auto && uploadUrl) {
            await uploadFiles(files);
        }
        // Reset the input so the same file can be selected again
        if (fileInputRef.current) {
            fileInputRef.current.value = "";
        }
    };
    const uploadFiles = async (files) => {
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            if (!file)
                continue;
            const formData = new FormData();
            formData.append("file", file);
            try {
                const response = await fetch(uploadUrl, {
                    method: "POST",
                    body: formData,
                });
                if (response.ok) {
                    const result = await response.text();
                    onUpload?.({
                        xhr: {
                            responseText: result,
                        },
                    });
                }
                else {
                    console.error("Upload failed:", response.statusText);
                }
            }
            catch (error) {
                console.error("Upload error:", error);
            }
        }
    };
    return (_jsxs(_Fragment, { children: [_jsx("input", { ref: fileInputRef, type: "file", accept: accept, multiple: multiple, onChange: handleFileChange, style: { display: "none" } }), _jsx(Button, { className: cn(className), variant: variant, size: size, onClick: handleButtonClick, disabled: disabled, ...props, children: children || (_jsxs(_Fragment, { children: [_jsx(Upload, { strokeWidth: 1 }), "Upload"] })) })] }));
}
export { UploadButton };
//# sourceMappingURL=upload-button.js.map