import { ExclamationTriangleIcon } from '@heroicons/react/24/outline';
import React, { useEffect, useState } from 'react';
import { FormUpload } from './FormUpload';
import { classNames } from '../types';
import { PHXCard } from '../Card';
import { PHXModal } from '../Modal';
export 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 = classNames(size === 'small' && 'sm:max-w-lg');
    const [link, setLink] = useState([]);
    const [isImage, setIsImage] = useState(fileType === 'image');
    const [showImage, setShowImage] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [length, setLength] = useState(0);
    const [isChecked, setIsChecked] = useState(false);
    const [selectedImages, setSelectedImages] = 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);
    };
    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]);
    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.createElement("div", { className: sizeModal },
        inCard ? (React.createElement(PHXCard, { headerAction: fileType === 'excel' ? { onClick: headerActionFunc, content: titleHeaderAction } : {}, isHeaderDownload: isHeaderDownload, primaryHeader: titleHeaderAction !== undefined, title: title },
            React.createElement(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.createElement(React.Fragment, null,
            React.createElement(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.createElement(PHXModal, { dangerActionText: 'X\u00E1c nh\u1EADn x\u00F3a', onDangerClick: handleDeleteImages, onHide: () => setIsModalOpen(false), primaryActionText: '', show: isModalOpen, title: 'Xo\u00E1 \u1EA3nh?' },
            React.createElement("div", { className: 'sm:flex sm:items-start' },
                !hiddenWarnIcon && (React.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.createElement(ExclamationTriangleIcon, { "aria-hidden": 'true', className: 'h-6 w-6 text-red-600' }))),
                React.createElement("div", { className: `mt-3 ${!hiddenWarnIcon ? 'text-center sm:ml-4' : ''} sm:mt-0 sm:text-left` },
                    React.createElement("div", { className: 'mt-2' },
                        React.createElement("p", { className: 'text-xs text-gray-600' }, contentOfModal ? contentOfModal : 'Bạn không thể hoàn tác thao tác này.')))))));
};
//# sourceMappingURL=UploadFile.js.map