"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UploadFile = void 0;
const tslib_1 = require("tslib");
const outline_1 = require("@heroicons/react/24/outline");
const react_1 = tslib_1.__importStar(require("react"));
const FormUpload_1 = require("./FormUpload");
const types_1 = require("../types");
const Card_1 = require("../Card");
const Modal_1 = require("../Modal");
const UploadFile = ({ apiCdnUpload, basePath, contentOfModal, defaultLink, fileName, fileType = 'image', handleListenUpload, headerActionFunc, helpText, inCard = true, isHeaderDownload = false, label, moduleId, multiImg = false, oneImg = false, projectId, setLoading, size, title, titleHeaderAction, isHorizontalLayout = false, cdnUploadType = 'file', customNextImage, actionTextDelete = false, twoColumn = false, hiddenWarnIcon = false, disabled = false, }) => {
    const sizeModal = (0, types_1.classNames)(size === 'small' && 'sm:max-w-lg');
    const [link, setLink] = (0, react_1.useState)([]);
    const [isImage, setIsImage] = (0, react_1.useState)(fileType === 'image');
    const [showImage, setShowImage] = (0, react_1.useState)(false);
    const [isModalOpen, setIsModalOpen] = (0, react_1.useState)(false);
    const [length, setLength] = (0, react_1.useState)(0);
    const [isChecked, setIsChecked] = (0, react_1.useState)(false);
    const [selectedImages, setSelectedImages] = (0, react_1.useState)([]);
    const handleCheckboxChange = (index) => {
        const updatedSelectedImages = [...selectedImages];
        if (updatedSelectedImages.includes(index)) {
            updatedSelectedImages.splice(updatedSelectedImages.indexOf(index), 1);
        }
        else {
            updatedSelectedImages.push(index);
        }
        setSelectedImages(updatedSelectedImages);
        setIsChecked(!isChecked);
        setLength(updatedSelectedImages === null || updatedSelectedImages === void 0 ? void 0 : updatedSelectedImages.length);
    };
    const handleFileChange = async (event) => {
        const selectedFile = event.target.files[0];
        if (selectedFile) {
            event.target.value = '';
            try {
                const dataSubmit = new FormData();
                dataSubmit.append('projectId', projectId);
                dataSubmit.append('moduleId', moduleId);
                dataSubmit.append('file', selectedFile);
                const response = await fetch(basePath + apiCdnUpload, {
                    method: 'POST',
                    body: dataSubmit,
                });
                if (response.ok) {
                    const responseData = await response.json();
                    const res = await responseData.link;
                    // update cdn avatar
                    if (cdnUploadType === 'avatar') {
                        handleListenUpload(selectedFile, responseData);
                        const [, , sizeDefault] = responseData.results;
                        setLink([sizeDefault.link]);
                        return;
                    }
                    // response upload file default
                    if (multiImg) {
                        handleListenUpload(selectedFile, [...link, res]);
                        setLink((prev) => [...prev, res]);
                    }
                    else {
                        handleListenUpload(selectedFile, [res]);
                        setLink([res]);
                    }
                }
                else {
                    console.error('Request failed with status:', response.status);
                }
            }
            catch (error) {
                console.error(error);
            }
        }
    };
    const handleDeleteImages = () => {
        const updatedLink = link.filter((_, index) => !selectedImages.includes(index));
        handleListenUpload('', oneImg ? [] : updatedLink);
        setLink(oneImg ? [] : updatedLink);
        // if (oneImg) {
        //   setIsImage(false);
        // }
        setSelectedImages([]);
        setIsModalOpen(false);
    };
    (0, react_1.useEffect)(() => {
        var _a;
        if (fileName) {
            const fileExtension = (_a = fileName.split('.').pop()) === null || _a === void 0 ? void 0 : _a.toLowerCase();
            const isImageExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExtension);
            setIsImage(isImageExt);
            setShowImage(false);
            const timer = setTimeout(() => {
                setShowImage(true);
            }, 1000);
            return () => clearTimeout(timer);
        }
        else {
            if (setLoading) {
                setLoading(true);
                setShowImage(false);
                const timer = setTimeout(() => {
                    setShowImage(true);
                    setLoading(false);
                }, 1000);
                return () => clearTimeout(timer);
            }
        }
        return;
    }, [fileName, link]);
    (0, react_1.useEffect)(() => {
        var _a, _b, _c;
        if (defaultLink && defaultLink.length > 0) {
            setLink(defaultLink);
            const defaultLinkEx = (_c = (_b = (_a = defaultLink === null || defaultLink === void 0 ? void 0 : defaultLink[0]) === null || _a === void 0 ? void 0 : _a.split('.')) === null || _b === void 0 ? void 0 : _b.pop()) === null || _c === void 0 ? void 0 : _c.toLowerCase();
            const isImageExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(defaultLinkEx);
            setIsImage(isImageExt);
            setShowImage(false);
            const timer = setTimeout(() => {
                setShowImage(true);
            }, 1000);
            return () => clearTimeout(timer);
        }
        else {
            return;
        }
    }, []);
    return (react_1.default.createElement("div", { className: sizeModal },
        inCard ? (react_1.default.createElement(Card_1.PHXCard, { headerAction: fileType === 'excel' ? { onClick: headerActionFunc, content: titleHeaderAction } : {}, isHeaderDownload: isHeaderDownload, primaryHeader: titleHeaderAction !== undefined, title: title },
            react_1.default.createElement(FormUpload_1.FormUpload, { disabled: disabled, customNextImage: customNextImage, fileName: fileName, fileType: fileType, handleCheckboxChange: handleCheckboxChange, handleFileChange: handleFileChange, helpText: helpText, isImage: isImage, isHorizontalLayout: isHorizontalLayout, label: label, length: length, link: link, oneImg: oneImg, selectedImages: selectedImages, setIsModalOpen: setIsModalOpen, showImage: showImage, actionTextDelete: actionTextDelete, twoColumn: twoColumn }))) : (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement(FormUpload_1.FormUpload, { disabled: disabled, customNextImage: customNextImage, fileName: fileName, fileType: fileType, handleCheckboxChange: handleCheckboxChange, handleFileChange: handleFileChange, helpText: helpText, isImage: isImage, label: label, isHorizontalLayout: isHorizontalLayout, length: length, link: link, oneImg: oneImg, selectedImages: selectedImages, setIsModalOpen: setIsModalOpen, showImage: showImage }))),
        react_1.default.createElement(Modal_1.PHXModal, { dangerActionText: 'X\u00E1c nh\u1EADn x\u00F3a', onDangerClick: handleDeleteImages, onHide: () => setIsModalOpen(false), primaryActionText: '', show: isModalOpen, title: 'Xo\u00E1 \u1EA3nh?' },
            react_1.default.createElement("div", { className: 'sm:flex sm:items-start' },
                !hiddenWarnIcon && (react_1.default.createElement("div", { className: 'mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10' },
                    react_1.default.createElement(outline_1.ExclamationTriangleIcon, { "aria-hidden": 'true', className: 'h-6 w-6 text-red-600' }))),
                react_1.default.createElement("div", { className: `mt-3 ${!hiddenWarnIcon ? 'text-center sm:ml-4' : ''} sm:mt-0 sm:text-left` },
                    react_1.default.createElement("div", { className: 'mt-2' },
                        react_1.default.createElement("p", { className: 'text-xs text-gray-600' }, contentOfModal ? contentOfModal : 'Bạn không thể hoàn tác thao tác này.')))))));
};
exports.UploadFile = UploadFile;
//# sourceMappingURL=UploadFile.js.map