import { __awaiter } from "tslib";
import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { Box, Button, Circle, CircularProgress, CircularProgressLabel, Icon, Input, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, ModalOverlay, Spacer, Text, Tab, TabList, TabPanel, TabPanels, Tabs, } from "@chakra-ui/react";
import { Delete, FileBlank, Upload } from "@feedloop/icon";
import React from "react";
import { useDropzone } from "react-dropzone";
import qoreStorageClient from "../hooks/qoreStorageClient";
import { ImageUploaderTriggerContext } from "@qorebase/app-runtime/src/hooks/useImageUploadTrigger";
const initialTabs = [
    { type: "Upload", url: "", file: null, progress: 0 },
    { type: "URL", url: "" },
];
const UploadTab = (props) => {
    const [file, setFile] = React.useState(null);
    const [progress, setProgress] = React.useState(0);
    const { user } = qoreStorageClient.useCurrentUser();
    const client = qoreStorageClient.useClient();
    const fileTable = qoreStorageClient.table("files");
    const insertFile = fileTable.useInsertRow();
    const onDrop = React.useCallback((files) => __awaiter(void 0, void 0, void 0, function* () {
        var _a, _b;
        const file = files[0];
        if (!file || !user)
            return;
        setFile(file);
        try {
            const result = yield insertFile.insertRow({
                user_files: user.id,
            });
            const fileRow = (_b = (_a = result.results) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b[0];
            const uploadToken = yield client.project.axios({
                baseURL: client.project.config.endpoint,
                url: `/v1/files/token/table/files/id/${fileRow.id}/column/file?access=write`,
                method: "GET",
            });
            const formData = new FormData();
            formData.append(file.name, file);
            yield client.project.axios.post(`/v1/files/upload?token=${uploadToken.data.token}`, formData, {
                baseURL: client.project.config.endpoint,
                headers: {
                    "Content-Type": "multipart/form-data",
                },
                onUploadProgress: (event) => {
                    setProgress(Math.round((event.loaded / event.total) * 100));
                },
            });
            props.onChange(`${client.project.config.endpoint}/v1/files/public/files/${fileRow.id}/file/${file.name}`);
        }
        catch (e) {
            setFile(null);
            setProgress(0);
        }
    }), [client, insertFile, user, props.onChange]);
    const { getRootProps, getInputProps } = useDropzone({
        onDrop,
        maxSize: 10000000,
        multiple: false,
        accept: "image/jpeg, image/png",
    });
    return file ? (_jsxs(Box, Object.assign({ display: "flex", flexDirection: "row", mt: 2, border: "1px", borderRadius: "md", borderColor: "rgb(226, 232, 240)", paddingY: "5", paddingX: "3" }, { children: [_jsx(Circle, Object.assign({ size: "12", mr: "5" }, { children: _jsx(Icon, { as: FileBlank, boxSize: 7, color: "black" }) })), _jsx(Box, Object.assign({ width: "44", wordBreak: "break-word" }, { children: _jsx(Text, Object.assign({ fontWeight: "bold", cursor: "pointer" }, { children: file.name })) })), _jsx(Spacer, {}), _jsx(Box, { children: progress === 100 ? (_jsx(Circle, Object.assign({ size: "12", bgColor: "blue.50", onClick: () => {
                        setFile(null);
                        setProgress(0);
                        props.onChange("");
                    }, cursor: "pointer" }, { children: _jsx(Icon, { as: Delete, boxSize: 5, textColor: "brand.900", "data-test": "file-picker-delete" }) }))) : (_jsx(CircularProgress, Object.assign({ value: progress, rounded: "full", bgColor: "blue.50", placeSelf: "end" }, { children: _jsx(CircularProgressLabel, { cursor: "pointer" }) }))) })] }))) : (_jsxs(Box, Object.assign({}, getRootProps({ className: "dropzone" }), { display: "flex", flexDirection: "column", alignItems: "center", mt: 2, cursor: "pointer", border: "1px", borderRadius: "md", borderColor: "rgb(226, 232, 240)", paddingY: "10" }, { children: [_jsx("input", Object.assign({}, getInputProps(), { "data-test": "file-picker-input" })), _jsx(Icon, { as: Upload, boxSize: 10, color: "blue.500", "data-test": "file-picker-input-icon" }), _jsx(Text, Object.assign({ pt: 10, w: "full", noOfLines: 1, align: "center" }, { children: "Drop your file here or Browse" })), _jsx(Text, Object.assign({ color: "blackAlpha.600" }, { children: "Maximum size: 10MB" }))] })));
};
const ImageUploader = (props) => {
    const [tab, setTab] = React.useState(initialTabs[0]);
    const [callback, setCallback] = React.useState(null);
    const triggerUpload = React.useCallback((callback) => setCallback(() => callback), []);
    const closeModal = React.useCallback(() => setCallback(null), []);
    return (_jsxs(ImageUploaderTriggerContext.Provider, Object.assign({ value: triggerUpload }, { children: [props.children, _jsxs(Modal, Object.assign({ isOpen: !!callback, onClose: closeModal }, { children: [_jsx(ModalOverlay, {}), _jsxs(ModalContent, Object.assign({ width: 428, maxW: "full" }, { children: [_jsx(ModalHeader, Object.assign({ fontSize: "lg" }, { children: "Upload Image" })), _jsx(ModalBody, { children: _jsxs(Tabs, Object.assign({ index: initialTabs.findIndex((t) => t.type === tab.type) || 0, onChange: (i) => setTab(initialTabs[i]), isLazy: true }, { children: [_jsx(TabList, { children: initialTabs.map((tab) => (_jsx(Tab, { children: tab.type }, tab.type))) }), _jsxs(TabPanels, { children: [_jsx(TabPanel, Object.assign({ px: 0 }, { children: _jsx(UploadTab, { onChange: (url) => setTab((tab) => tab.type === "Upload" ? Object.assign(Object.assign({}, tab), { url }) : tab) }) })), _jsx(TabPanel, Object.assign({ px: 0 }, { children: _jsx(Input, { w: "full", placeholder: "Image URL", onChange: (e) => setTab((tab) => tab.type === "URL"
                                                            ? Object.assign(Object.assign({}, tab), { url: e.target.value }) : tab), size: "sm" }) }))] })] })) }), _jsxs(ModalFooter, { children: [_jsx(Button, Object.assign({ variant: "outline", mr: 3, onClick: closeModal, size: "sm" }, { children: "Close" })), _jsx(Button, Object.assign({ variant: "solid", colorScheme: "blue", disabled: !tab.url, onClick: () => {
                                            callback(tab.url);
                                            closeModal();
                                        }, size: "sm" }, { children: "Save" }))] })] }))] }))] })));
};
export default ImageUploader;
//# sourceMappingURL=ImageUploader.js.map