import DomOutline from "./DomOutline";

const {useState, useRef} = React;

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

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

    const updateVideo = (video) => {
        setCurrentItem(index);

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

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

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

            let src = element.tagName === 'VIDEO' ? element.currentSrc : jQuery(element).find('iframe').attr('src');

            const youtubeRegex = /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$/gi;
            const isYoutube = src.match(youtubeRegex);

            const vimeoRegex = /^(https?:\/\/)?(((player\.)?vimeo\.com\/video\/)|(vimeo\.com\/))([0-9]+)/gi;
            const isVimeo = src.match(vimeoRegex);

            const dailymotionRegex = /^(https?:\/\/)?(www\.)?(dailymotion\.com)\/.+$/gi;
            const isDailymotion = src.match(dailymotionRegex);

            if (isYoutube) {
                const youtubeUrl = /youtube.com\/(v|embed)\/([^?&"]+)/.exec(src)[2];

                if (!youtubeUrl) {
                    showModal();
                    return;
                }

                src = `https://youtube.com/watch?v=${youtubeUrl}`;
            }

            if (isVimeo) {
                let vimeoUrl = /player.vimeo.com\/video\/([^?&"]+)/.exec(src)[1];

                if (!vimeoUrl) {
                    showModal();
                    return;
                }

                src = `https://vimeo.com/${vimeoUrl}`;
            }

            if (isDailymotion) {
                let dailymotionUrl = /(?:dailymotion\.com\/embed\/video\/)([\w-]+)/.exec(src)[1];

                if (!dailymotionUrl) {
                    showModal();
                    return;
                }

                src = `https://dailymotion.com/video/${dailymotionUrl}`;
            }

            if (src) {
                updateVideo(src);
            } else {
                showModal();
            }

        },
    }));


    return (
        <button type={`button`}
                className={`dracula-btn select-video ${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>
    )
}