'use client'

import {useState, useEffect, forwardRef} from 'react'
import PropTypes from 'prop-types'
import Fab from '@mui/material/Fab'
import Dialog from '@mui/material/Dialog'
import Slide from '@mui/material/Slide'
import Box from '@mui/material/Box'
import Skeleton from '@mui/material/Skeleton'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import Tooltip from '@mui/material/Tooltip'
import useMediaQuery from '@mui/material/useMediaQuery'
import {useTheme, keyframes} from '@mui/material/styles'
import MicIcon from '@mui/icons-material/Mic'
import CloseIcon from '@mui/icons-material/Close'

const pulse = keyframes`
  0%, 100% { opacity: 0.18; transform: scale(1); }
  50% { opacity: 0.55; transform: scale(1.2); }
`

const SlideUp = forwardRef(function SlideUp(props, ref) {
  return <Slide ref={ref} direction='up' {...props} />
})

function toEmbedUrl(url) {
  try {
    const u = new URL(url)
    const match = u.pathname.match(/\/(?:videos\/watch|w)\/([^/?#]+)/)
    if (match) {
      return `${u.origin}/videos/embed/${match[1]}?title=0&warningTitle=0&peertubeLink=0&controlBar=1`
    }

    return url
  } catch {
    return url
  }
}

export default function KaraokeModal({url, desktopUrl, titre, artistes}) {
  const [open, setOpen] = useState(false)
  const [loaded, setLoaded] = useState(false)
  const theme = useTheme()
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'))
  const activeUrl = (!isMobile && desktopUrl) ? desktopUrl : url

  useEffect(() => {
    if (!open) {
      setLoaded(false)
    }
  }, [open])

  return (
    <>
      <Tooltip title='Karaoké' placement='left'>
        <Fab
          color='primary'
          size={isMobile ? 'medium' : 'large'}
          aria-label='karaoké'
          sx={{
            position: 'fixed',
            bottom: {xs: 24, sm: 32},
            right: {xs: 24, sm: 32},
            zIndex: 1050,
          }}
          onClick={() => setOpen(true)}
        >
          <MicIcon />
        </Fab>
      </Tooltip>

      <Dialog
        open={open}
        slots={{transition: SlideUp}}
        maxWidth={false}
        sx={{
          '& .MuiDialog-container': {
            alignItems: {xs: 'flex-end', sm: 'center'},
          }
        }}
        slotProps={{
          backdrop: {sx: {backdropFilter: 'blur(6px)', bgcolor: 'rgba(0,0,0,0.85)'}},
          paper: {
            sx: {
              bgcolor: '#000',
              overflow: 'hidden',
              ...(isMobile ? {
                width: '100vw',
                height: '100dvh',
                maxWidth: 'none',
                maxHeight: 'none',
                m: 0,
                borderRadius: 0,
                boxShadow: 'none',
              } : {
                width: 'calc(80vh * 16 / 9)',
                height: '80vh',
                maxWidth: 'none',
                maxHeight: 'none',
                borderRadius: '16px',
                boxShadow: '0 24px 64px rgba(0,0,0,0.7)',
              })
            }
          }
        }}
        onClose={() => setOpen(false)}
      >
        {/* Header superposé en gradient */}
        <Box sx={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          zIndex: 2,
          px: 2,
          pt: 2,
          pb: 4,
          background: 'linear-gradient(to bottom, rgba(0,0,0,0.8) 0%, transparent 100%)',
          display: 'flex',
          alignItems: 'flex-start',
          justifyContent: 'space-between',
          pointerEvents: 'none',
        }}
        >
          <Box sx={{pointerEvents: 'none'}}>
            {titre && (
              <Typography variant='subtitle1' sx={{color: '#fff', fontWeight: 700, lineHeight: 1.2, textShadow: '0 1px 4px rgba(0,0,0,0.5)'}}>
                {titre}
              </Typography>
            )}
            {artistes?.length > 0 && (
              <Typography variant='caption' sx={{color: 'rgba(255,255,255,0.65)', textShadow: '0 1px 4px rgba(0,0,0,0.5)'}}>
                {artistes.map(a => a.alias).join(', ')}
              </Typography>
            )}
          </Box>
          <IconButton
            size='small'
            aria-label='fermer'
            sx={{
              pointerEvents: 'auto',
              color: '#fff',
              bgcolor: 'rgba(255,255,255,0.15)',
              backdropFilter: 'blur(8px)',
              border: '1px solid rgba(255,255,255,0.12)',
              '&:hover': {bgcolor: 'rgba(255,255,255,0.25)'},
            }}
            onClick={() => setOpen(false)}
          >
            <CloseIcon fontSize='small' />
          </IconButton>
        </Box>

        {open && (
          <Box sx={{position: 'absolute', inset: 0, overflow: 'hidden'}}>
            {!loaded && (
              <>
                <Skeleton
                  variant='rectangular'
                  animation='wave'
                  sx={{position: 'absolute', inset: 0, bgcolor: 'rgba(255,255,255,0.06)', transform: 'none'}}
                />
                <Box sx={{
                  position: 'absolute',
                  inset: 0,
                  zIndex: 1,
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: 1.5,
                }}
                >
                  <MicIcon sx={{fontSize: 44, color: 'rgba(255,255,255,0.55)', animation: `${pulse} 1.6s ease-in-out infinite`}} />
                  <Typography
                    variant='caption'
                    sx={{color: 'rgba(255,255,255,0.35)', letterSpacing: '0.15em', textTransform: 'uppercase'}}
                  >
                    Chargement…
                  </Typography>
                </Box>
              </>
            )}

            {isMobile ? (
              /* Vidéo verticale : scale le player 16:9 à la hauteur du portrait et croppe les côtés */
              <Box sx={{
                position: 'absolute',
                top: 0,
                left: '50%',
                transform: 'translateX(-50%)',
                height: '100%',
                aspectRatio: '16 / 9',
              }}
              >
                <iframe
                  allowFullScreen
                  src={toEmbedUrl(activeUrl)}
                  style={{width: '100%', height: '100%', border: 'none', display: 'block', opacity: loaded ? 1 : 0, transition: 'opacity 0.4s ease'}}
                  allow='autoplay; fullscreen'
                  sandbox='allow-same-origin allow-scripts allow-popups allow-forms'
                  title='Karaoké'
                  onLoad={() => setLoaded(true)}
                />
              </Box>
            ) : (
              /* Vidéo 16:9 desktop : player remplit exactement le dialog paysage */
              <iframe
                allowFullScreen
                src={toEmbedUrl(activeUrl)}
                style={{width: '100%', height: '100%', border: 'none', display: 'block', opacity: loaded ? 1 : 0, transition: 'opacity 0.4s ease'}}
                allow='autoplay; fullscreen'
                sandbox='allow-same-origin allow-scripts allow-popups allow-forms'
                title='Karaoké'
                onLoad={() => setLoaded(true)}
              />
            )}
          </Box>
        )}
      </Dialog>
    </>
  )
}

KaraokeModal.propTypes = {
  url: PropTypes.string.isRequired,
  desktopUrl: PropTypes.string,
  titre: PropTypes.string,
  artistes: PropTypes.array,
}
