import React, { useEffect, useRef, useState } from 'react'
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  Button,
  Kbd,
  useToast,
  Spacer,
  Flex,
} from '@chakra-ui/react'

import DisconnectButton from './DisconnectButton'
import ObraModalContent from './ObraModalContent'

import useStore from '../store'

const MenuOverlay: React.FC = () => {
  const continueButton = useRef<HTMLButtonElement>(null)
  const [helpToastShown, setHelpToastShown] = useState<boolean>(false)
  const pointerLockControls = useStore((state) => state.pointerLockControls)
  const pointerLocked = useStore((state) => state.pointerLocked)
  const modalObra = useStore((state) => state.modalObra)
  const setModalObra = useStore((state) => state.setModalObra)
  const toast = useToast()

  useEffect(() => {
    if (!helpToastShown && pointerLocked) {
      toast({
        description: 'Para volver al menú, pulsá ESC',
        duration: 5000,
        isClosable: false,
      })
      setHelpToastShown(true)
    }
  }, [pointerLocked, helpToastShown])

  const lockControls = () => {
    if (pointerLockControls && !pointerLocked) {
      if (modalObra) {
        setModalObra(null)
      }
      pointerLockControls.lock?.()
    }
  }

  return (
    <>
      <Modal
        isOpen={!pointerLocked}
        onClose={() => undefined}
        size="xl"
        initialFocusRef={continueButton}
      >
        <ModalOverlay />
        <ModalContent>
          {modalObra ? (
            <ObraModalContent id={modalObra} />
          ) : (
            <>
              <ModalHeader>museo.red</ModalHeader>
              <ModalBody mb="2rem" mx="2rem" textAlign="center">
                Usa las teclas <Kbd>W</Kbd>, <Kbd>A</Kbd>, <Kbd>S</Kbd> y <Kbd>D</Kbd>{' '}
                para moverte. Usá el mouse para mirar alrededor
              </ModalBody>
            </>
          )}
          <ModalFooter as={Flex}>
            {!modalObra ? <DisconnectButton colorScheme="gray" /> : null}
            <Spacer />
            <Button
              colorScheme="blue"
              onClick={lockControls}
              size="lg"
              ref={continueButton}
            >
              Continuar
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  )
}

export default MenuOverlay
