"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileInput = void 0;
const react_1 = __importStar(require("react"));
const icons_1 = require("../../icons");
const varsUtilities_1 = require("../../varsUtilities");
const inlines_1 = require("inlines");
const react_2 = require("@based/react");
const Text_1 = require("../Text");
const __1 = require("..");
function FileInput({ onChange }) {
    const client = (0, react_2.useClient)();
    const inputRef = (0, react_1.useRef)(null);
    const [file, setFile] = (0, react_1.useState)(null);
    const [filePreview, setFilePreview] = (0, react_1.useState)(null);
    const [uploadProgress, setUploadProgress] = (0, react_1.useState)(0);
    const [status, setStatus] = (0, react_1.useState)('initial');
    // console.log(status)
    return (react_1.default.createElement(inlines_1.styled.label, { style: {
            position: 'relative',
            display: 'flex',
            flexDirection: 'column',
            color: (0, varsUtilities_1.color)('content', 'default', 'primary'),
        } },
        react_1.default.createElement(inlines_1.styled.div, { style: {
                padding: '8px 12px',
                borderRadius: 8,
                ...(status === 'initial' && {
                    cursor: 'pointer',
                    border: `1px dashed ${(0, varsUtilities_1.color)('inputBorder', 'neutralNormal', 'default')}`,
                    '&:hover': {
                        border: `1px dashed ${(0, varsUtilities_1.color)('inputBorder', 'neutralHover', 'default')}`,
                    },
                }),
                ...(status === 'error' && {
                    cursor: 'pointer',
                    border: `1px dashed ${(0, varsUtilities_1.color)('inputBorder', 'alert', 'default')}`,
                    '&:hover': {
                        border: `1px dashed ${(0, varsUtilities_1.color)('inputBorder', 'alert', 'default')}`,
                    },
                }),
                ...(status === 'uploading' && {
                    border: `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralNormal', 'default')}`,
                }),
                ...(status === 'success' && {
                    border: `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralNormal', 'default')}`,
                }),
            } },
            status === 'initial' && (react_1.default.createElement(inlines_1.styled.div, { style: {
                    display: 'flex',
                    alignItems: 'center',
                    '& > * + *': { marginLeft: '8px' },
                } },
                react_1.default.createElement(icons_1.IconUpload, null),
                react_1.default.createElement(Text_1.Text, null, "Upload new file"))),
            status === 'error' && (react_1.default.createElement(inlines_1.styled.div, { style: {
                    display: 'flex',
                    alignItems: 'center',
                    '& > * + *': { marginLeft: '8px' },
                } },
                react_1.default.createElement(icons_1.IconUpload, null),
                react_1.default.createElement(Text_1.Text, null, "An error has occured"))),
            status === 'uploading' && (react_1.default.createElement(inlines_1.styled.div, { style: {
                    display: 'flex',
                    alignItems: 'center',
                    '& > * + *': { marginLeft: '8px' },
                } },
                react_1.default.createElement("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "none", style: { transform: 'rotate(270deg)' } },
                    react_1.default.createElement("circle", { cx: "10", cy: "10", r: "7", stroke: (0, varsUtilities_1.color)('action', 'neutral', 'subtleNormal'), strokeWidth: "2" }),
                    react_1.default.createElement("circle", { cx: "10", cy: "10", r: "7", stroke: (0, varsUtilities_1.color)('action', 'primary', 'normal'), strokeWidth: "2", strokeLinecap: "round", pathLength: "100", strokeDasharray: "100", strokeDashoffset: 100 - (5 + uploadProgress * 0.95) })),
                react_1.default.createElement(Text_1.Text, null, "Uploading..."))),
            status === 'success' && (react_1.default.createElement(inlines_1.styled.div, { style: {
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    '& > * + *': { marginLeft: '8px' },
                } },
                filePreview ? (react_1.default.createElement(inlines_1.styled.img, { src: filePreview, style: {
                        height: 48,
                        width: 48,
                        borderRadius: 4,
                        objectFit: 'cover',
                    } })) : (react_1.default.createElement(icons_1.IconAttachment, null)),
                react_1.default.createElement(Text_1.Text, null, file?.name),
                react_1.default.createElement(__1.Dropdown.Root, null,
                    react_1.default.createElement(__1.Dropdown.Trigger, null,
                        react_1.default.createElement(inlines_1.styled.div, { type: "button", style: {
                                display: 'flex',
                                justifyContent: 'center',
                                alignItems: 'center',
                                border: 'none',
                                outline: 'none',
                                background: 'transparent',
                                padding: '2px',
                                borderRadius: 4,
                                marginLeft: 'auto',
                                cursor: 'pointer',
                                color: (0, varsUtilities_1.color)('content', 'default', 'primary'),
                                '&:hover': {
                                    background: (0, varsUtilities_1.color)('action', 'system', 'hover'),
                                },
                            } },
                            react_1.default.createElement(icons_1.IconMoreHorizontal, null))),
                    react_1.default.createElement(__1.Dropdown.Items, null,
                        react_1.default.createElement(__1.Dropdown.Item, { icon: react_1.default.createElement(icons_1.IconOpenInNew, null), onClick: () => {
                                const url = URL.createObjectURL(file);
                                window.open(url, '_blank', 'noopener,noreferrer');
                            } }, "Open in new tab"),
                        react_1.default.createElement(__1.Dropdown.Item, { icon: react_1.default.createElement(icons_1.IconDownload, null), onClick: () => {
                                const url = URL.createObjectURL(file);
                                const link = document.createElement('a');
                                link.download = file.name;
                                link.href = url;
                                link.click();
                            } }, "Download"),
                        react_1.default.createElement(__1.Dropdown.Separator, null),
                        react_1.default.createElement(__1.Dropdown.Item, { icon: react_1.default.createElement(icons_1.IconDelete, null), onClick: () => {
                                setStatus('initial');
                                setFile(null);
                                setFilePreview(null);
                                setUploadProgress(0);
                                onChange?.();
                                if (inputRef.current) {
                                    inputRef.current.value = '';
                                }
                            } }, "Delete")))))),
        react_1.default.createElement(inlines_1.styled.input, { type: "file", ref: inputRef, onChange: async (e) => {
                const file = e.target.files?.[0];
                if (!file)
                    return;
                setFile(file);
                try {
                    setStatus('uploading');
                    const { id, src } = await client.stream('db:file-upload', {
                        contents: file,
                    }, (value) => {
                        setUploadProgress(value * 100);
                    });
                    setStatus('success');
                    onChange?.({ id, src });
                    if (file.type.includes('image/')) {
                        const objectURL = URL.createObjectURL(file);
                        setFilePreview(objectURL);
                    }
                }
                catch {
                    setStatus('error');
                    setFile(null);
                    setFilePreview(null);
                    setUploadProgress(0);
                    if (inputRef.current) {
                        inputRef.current.value = '';
                    }
                }
            }, style: {
                position: 'absolute',
                width: '1px',
                height: '1px',
                padding: '0',
                margin: '-1px',
                overflow: 'hidden',
                clip: 'rect(0, 0, 0, 0)',
                whiteSpace: 'nowrap',
                borderWidth: '0',
            } })));
}
exports.FileInput = FileInput;
//# sourceMappingURL=FileInput.js.map