import React from 'react'
import ReactDOM from 'react-dom/client'
import {useState, useEffect, createElement} from '@wordpress/element'
import VideoSearch from "./Components/VideoSearchComponent/VideoSearchComponent"
import {Button, Modal} from '@wordpress/components'

const AddDailymotionPlayer = () => {

    const [isOpen, setIsOpen] = useState(false)

    useEffect(() => {
        const handleVideoUpdated = () => {
            setIsOpen(false)
        }

        document.addEventListener('dm-video-updated', handleVideoUpdated)

        return () => {
            document.removeEventListener('dm-video-updated', handleVideoUpdated)
        }
    }, [])

    return (
        <>
            <Button className="button" id="insert-dailymotion" type="button" onClick={() => setIsOpen(true)}>
                <svg width="16" height="16" viewBox="0 0 96 96" xmlns="http://www.w3.org/2000/svg">
                    <path
                        d="M44,10H16c-1.1,0-2,0.9-2,2v12c0,0.5,0.2,1,0.6,1.4l12,12C27,37.8,27.5,38,28,38h16c5.5,0,10,4.5,10,10s-4.5,10-10,10H22c-1.1,0-2,0.9-2,2v12c0,0.5,0.2,1,0.6,1.4l12,12C33,85.8,33.5,86,34,86h10c21,0,38-17,38-38S65,10,44,10z M18,16.8l8,8v6.3l-8-8V16.8z M58,48c0-7.7-6.3-14-14-14H30v-8h14c12.1,0,22,9.9,22,22s-9.9,22-22,22h-9.2l-8-8H44C51.7,62,58,55.7,58,48z M24,64.8l8,8v6.3l-8-8V64.8z M44,82h-8v-8h8c14.3,0,26-11.7,26-26S58.3,22,44,22H28.8l-8-8H44c18.7,0,34,15.3,34,34S62.7,82,44,82z"
                        fill="#2271b1"/>
                </svg>
                Dailymotion</Button>
            {isOpen && (
                <Modal className="popup__content-finder" isFullscreen={true} __experimentalHideHeader={true} onRequestClose={() => setIsOpen(false)}>
                    <VideoSearch/>
                </Modal>
            )}
        </>
    )
}

window.addEventListener('load', () => {
    // Hook modal button to editor tools
    const wpEditorTools = document.getElementById('wp-content-editor-tools')
    const placeHolder = document.createElement('span')
    placeHolder.id = 'dm-search-classic'

    wpEditorTools.appendChild(placeHolder)

    ReactDOM.createRoot(document.getElementById('dm-search-classic')).render(<AddDailymotionPlayer/>);
})
