import DomOutline from "./DomOutline";

const {useState, useRef} = React;

export default function SelectImage({data, setData, index, setCurrentItem}) {
    const {images = [{}]} = data;

    const [isActive, setIsActive] = useState(false);

    const updateImage = (image) => {
        setCurrentItem(index);

        setData({
            ...data,
            images: [...images.slice(0, index), {...images[index], 'light': image}, ...images.slice(index + 1)]
        });
    }

    const DomeOutlineRef = useRef(DomOutline({
        filter: 'img',
        onClick: (event, element) => {
            setIsActive(false);

            const showModal = () => {
                Swal.fire({
                    title: wp.i18n.__('Sorry, No image found!', 'dracula-dark-mode'),
                    text: wp.i18n.__('Please try to insert the image link manually.', 'dracula-dark-mode'),
                    icon: 'error',
                    confirmButtonText: wp.i18n.__('Ok', 'dracula-dark-mode'),
                    customClass: {
                        container: 'dracula-swal',
                    },
                });
            }

            const image = element.src || jQuery(element).css('background-image').replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];

            if (image) {
                updateImage(image);
            } else {
                showModal();
            }

        },
    }));


    return (
        <button
            type={`button`}
            className={`dracula-btn select-image ${isActive ? 'active' : ''} input-group-append`}
            onClick={() => {
                if (isActive) {
                    setIsActive(false);
                    DomeOutlineRef.current.stop();
                } else {
                    setIsActive(true);
                    DomeOutlineRef.current.start();
                }
            }}>

            {isActive ?
                <span className="dashicons dashicons-no-alt"/>
                :
                <span className="dracula-btn-icon icon-select-elements"></span>
            }
        </button>
    )
}