import React, { useEffect, useRef, useState } from 'react';
import { PHXSpinner } from '../Loading';
import { PHXButton } from '../Button';
import { SIZE_DEFAULT } from '../../utils/constants';
export default function PHXUploadAvatar({ apiCdnUpload, basePath, defaultValue, handleListenUpload, moduleId, }) {
    const [link, setLink] = useState('');
    const inputRef = useRef(null);
    const defaultAvatar = 'https://static-data-sisv2.phx-smartschool.com/common/prod/avatar/default_avatar.png';
    const [loading, setLoading] = useState(false);
    const handleUploadAvatar = async (e) => {
        setLoading(true);
        const files = e.target.files;
        const fileLength = files.length;
        if (files && fileLength !== 0) {
            const selectedFile = files[0];
            const formData = new FormData();
            formData.append('file', selectedFile);
            // @ts-ignore
            formData.append('moduleId', moduleId);
            try {
                const response = await fetch(basePath + apiCdnUpload, {
                    method: 'POST',
                    body: formData,
                });
                if (response.ok) {
                    const responseData = await response.json();
                    const res = await responseData.results;
                    const originalFile = res.find((item) => item.link.includes(SIZE_DEFAULT));
                    setLink(originalFile === null || originalFile === void 0 ? void 0 : originalFile.link);
                    handleListenUpload(res);
                }
                else {
                    console.error('Request failed with status:', response.status);
                }
            }
            catch (error) {
                console.error('Error:', error);
            }
        }
        setLoading(false);
    };
    const handleClick = () => {
        var _a;
        (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.click();
    };
    const handleDeleteImage = () => {
        setLink('');
        handleListenUpload(null);
    };
    useEffect(() => {
        if (defaultValue) {
            setLink(defaultValue);
        }
        else {
            return;
        }
    }, [defaultValue]);
    const [showLargeImage, setShowLargeImage] = useState(false);
    const [largeImageUrl, setLargeImageUrl] = useState('');
    useEffect(() => {
        const closeImageOnOutsideClick = (event) => {
            if (showLargeImage) {
                const clickedElement = event.target;
                const imageContainer = document.getElementById('large-image-container');
                if (!(imageContainer === null || imageContainer === void 0 ? void 0 : imageContainer.contains(clickedElement))) {
                    setShowLargeImage(false);
                }
            }
        };
        document.addEventListener('click', closeImageOnOutsideClick);
        return () => {
            document.removeEventListener('click', closeImageOnOutsideClick);
        };
    }, [showLargeImage]);
    const handleImageClick = (url) => {
        setLargeImageUrl(url);
        setShowLargeImage(true);
    };
    return (React.createElement("div", { className: ' items-center lg:flex xl:flex' },
        loading ? (React.createElement("div", { className: 'flex h-14 w-14 items-center justify-center rounded-full bg-gray-200' },
            React.createElement(PHXSpinner, { className: 'h-5 w-5' }))) : (React.createElement("div", { className: 'flex h-14 w-14 items-center justify-center overflow-hidden rounded-full hover:cursor-pointer' },
            React.createElement("img", { alt: 'avatar', className: 'w-full transition-all duration-300', src: link && !loading ? link : defaultAvatar, onClick: () => handleImageClick(link) }))),
        showLargeImage && (React.createElement("div", { className: 'fixed left-0 top-0 z-50 flex h-full w-full items-center justify-center bg-black bg-opacity-70', id: 'large-image-container', onClick: () => setShowLargeImage(false) },
            React.createElement("img", { alt: 'Large Image', className: 'max-h-full max-w-full', onClick: (e) => e.stopPropagation(), src: largeImageUrl }))),
        React.createElement("div", { className: 'flex lg:ml-3 xl:ml-3 2xl:ml-3 mt-4 lg:mt-0' },
            React.createElement(PHXButton, { className: 'lg:mr-3 ', onClick: handleClick, secondary: true, size: 'small' }, "T\u1EA3i \u1EA3nh l\u00EAn"),
            React.createElement("input", { ref: inputRef, className: 'hidden', id: 'file', onChange: handleUploadAvatar, type: 'file' }),
            defaultValue || link ? (React.createElement(PHXButton, { className: 'ml-3 lg:ml-0', onClick: handleDeleteImage, secondary: true, size: 'small' }, "X\u00F3a \u1EA3nh")) : null)));
}
//# sourceMappingURL=UploadAvatar.js.map