'use client'

import {useState, useEffect, forwardRef} from 'react'
import Link from 'next/link'
import PropTypes from 'prop-types'
import AppBar from '@mui/material/AppBar'
import Box from '@mui/material/Box'
import CssBaseline from '@mui/material/CssBaseline'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import MenuIcon from '@mui/icons-material/Menu'
import Toolbar from '@mui/material/Toolbar'
import MuiAlert from '@mui/material/Alert'
import Snackbar from '@mui/material/Snackbar'
import KeyboardBackspaceIcon from '@mui/icons-material/KeyboardBackspace'
import VweKouteAchte from './vwe-koute-achte'

import DrawerBar from './drawer-bar'
import Pataje from './pataje'
import KaraokeModal from './karaoke-modal'
import {useCurrentTrack} from './current-track-context'

const drawerWidth = 240

const Alert = forwardRef(function Alert(props, ref) {
  return <MuiAlert ref={ref} elevation={6} variant='filled' {...props} />
})

export default function TeksDrawer({paroles}) {
  const [parole] = useCurrentTrack()
  const [mobileOpen, setMobileOpen] = useState(false)
  const [open, setOpen] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  useEffect(() => {
    if (error || success) {
      setOpen(true)
    }
  }, [error, success, setOpen])

  const handleClose = (event, reason) => {
    if (reason === 'clickaway') {
      return
    }

    setOpen(false)
    setSuccess('')
    setError('')
  }

  const handleOpenDrawer = async () => {
    setMobileOpen(true)
  }

  const handleCloseDrawer = () => {
    setMobileOpen(false)
  }

  return (
    <Box sx={{display: 'flex'}}>
      <CssBaseline />
      <AppBar
        position='fixed'
        sx={{
          width: {sm: `calc(100% - ${drawerWidth}px)`},
          ml: {sm: `${drawerWidth}px`},
          borderTop: '2px solid #303030',
          marginTop: '3rem',
          zIndex: 1
        }}
      >
        <Toolbar>
          <Box sx={{display: 'flex', alignContent: 'center'}}>
            <IconButton
              color='inherit'
              aria-label='open drawer'
              edge='start'
              sx={{display: {sm: 'none'}}}
              onClick={handleOpenDrawer}
            >
              <MenuIcon />
            </IconButton>
            {parole && (
              <Link passHref prefetch={false} href='/paroles'>
                <IconButton aria-label='return' size='medium'>
                  <KeyboardBackspaceIcon style={{fontSize: '1.5em'}} />
                </IconButton>
              </Link>
            )}
          </Box>
          {parole && (
            <Box sx={{display: 'flex', position: 'relative', top: '-20px'}}>
              <Box>
                <Pataje parole={parole} setError={setError} setSuccess={setSuccess} />
              </Box>

              {parole.streamVideo && parole.streamVideo.length > 0 && (
                <Box>
                  <VweKouteAchte niVideyo parole={parole} />
                </Box>
              )}
              {parole.streamAudio && parole.streamAudio.length > 0 && (
                <Box>
                  <VweKouteAchte niOdyo parole={parole} />
                </Box>
              )}
            </Box>
          )}
        </Toolbar>
      </AppBar>
      <Box
        component='nav'
        sx={{width: {sm: drawerWidth}, flexShrink: {sm: 0}, padding: 0}}
        aria-label='mailbox folders'
      >
        <Drawer
          variant='temporary'
          open={mobileOpen}
          sx={{
            display: {xs: 'block', sm: 'none'},
            '& .MuiDrawer-paper': {boxSizing: 'border-box', width: drawerWidth}
          }}
          onClose={handleCloseDrawer}
        >
          <DrawerBar meteEsMobilOuve={setMobileOpen} paroles={paroles} />
        </Drawer>
        <Drawer
          open
          variant='permanent'
          sx={{
            display: {xs: 'none', sm: 'block'},
            '& .MuiDrawer-paper': {boxSizing: 'border-box', width: drawerWidth, marginTop: '3em', borderTop: '2px solid #303030'},
          }}
        >
          <DrawerBar meteEsMobilOuve={setMobileOpen} paroles={paroles} />
        </Drawer>
      </Box>
      {parole?.karaokeUrl && (
        <KaraokeModal url={parole.karaokeUrl} desktopUrl={parole.karaokeDesktopUrl} titre={parole.titre} artistes={parole.artistes} />
      )}
      {success && (
        <Snackbar open={open} autoHideDuration={3000} onClose={handleClose}>
          <Alert severity='success' onClose={handleClose}>
            <strong>{success}</strong>
          </Alert>
        </Snackbar>
      )}
      {error && (
        <Snackbar open={open} autoHideDuration={3000} onClose={handleClose}>
          <Alert severity='error' onClose={handleClose}>
            <strong>Une erreur s’est produite</strong> : <i>{error.message}</i>
          </Alert>
        </Snackbar>
      )}
    </Box>
  )
}

TeksDrawer.propTypes = {
  paroles: PropTypes.array,
}
