import React, { useState, useEffect } from 'react'
import journey from '../../assets/img/video-thumbnail.png'
import { Button, Card } from '@wordpress/components'
import YouTube, { YouTubeProps } from 'react-youtube'
import { closeSmall } from '@wordpress/icons'
import { useI18n } from '@wordpress/react-i18n'

const Video = () => {
  const [isOpen, setIsOpen] = useState(false)

  const { __ } = useI18n()
  const opts = {
    height: '390',
    width: '640',
    playerVars: {
      autoplay: 1,
    },
  }

  useEffect(() => {
    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && isOpen) {
        setIsOpen(false)
      }
    }

    window.addEventListener('keydown', handleEscape)
    return () => window.removeEventListener('keydown', handleEscape)
  }, [isOpen])

  const closeModal = () => setIsOpen(false)

  const onReady: YouTubeProps['onReady'] = event => {
    event.target.playVideo()
  }

  return (
    <div id="video-section">
      <Card className="mtl card-section">
        <div className="flex">
          <div className="video-thumbnail">
            <div className="button-container">
              <button
                aria-label="Play instruction movie"
                className="flex flex-dir-col align-ic justify-cc"
                onClick={event => {
                  event.preventDefault()
                  setIsOpen(true)
                }}
              >
                <div className="triangle" aria-hidden="true" />
              </button>
            </div>
          </div>
          <div className="mlm">
            <h2>
              {__(
                'How to setup Posten Bring Checkout',
                'posten-bring-checkout'
              )}{' '}
              🍿🎬
            </h2>
          </div>
        </div>
      </Card>
      {isOpen && (
        <div className="modal flex justify-cc align-ic">
          <div className="modal-content">
            <YouTube videoId="PMmryEvKf70" opts={opts} onReady={onReady} />
            <Button
              className="close-button"
              icon={closeSmall}
              onClick={closeModal}
            />
          </div>
        </div>
      )}
    </div>
  )
}

export default Video
