import PropTypes from 'prop-types'
import {useRouter} from 'next/router'

import {styled} from '@mui/material/styles'
import {List, ListItem, ListItemText} from '@mui/material'
import FiberNewOutlinedIcon from '@mui/icons-material/FiberNewOutlined'
import LibraryMusicIcon from '@mui/icons-material/LibraryMusic'
import ExplicitIcon from '@mui/icons-material/Explicit'

import {esBrandNew} from '../../lib/date'

const PREFIX = 'mizik-lis'

const classes = {
  root: `${PREFIX}-root`
}

const StyledList = styled(List)((
  {
    theme
  }
) => ({
  [`&.${classes.root}`]: {
    width: '100%',
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper
  }
}))

export default function MizikLis({meteEsMobilOuve, niAwtis, paroles, slugTeksChwazi, meteSlugTeksChwazi}) {
  const router = useRouter()

  const handleClick = slug => {
    if (meteSlugTeksChwazi) {
      meteSlugTeksChwazi(slug)
    }

    if (slug !== slugTeksChwazi) {
      if (niAwtis) {
        router.push(`/paroles/${slug}`).then(() => window.scrollTo(0, 0))
      } else {
        router.push(`/paroles/${slug}#${slug}`).then(() => window.scrollTo(0, 0))
      }
    }

    if (meteEsMobilOuve) {
      meteEsMobilOuve(false)
    }
  }

  return (
    <StyledList component='nav' className={classes.root} aria-label='mizik'>
      {paroles.map(({id, attributes}) => (
        <ListItem
          key={id}
          button
          id={attributes.slug}
          selected={slugTeksChwazi === attributes.slug}
          onClick={() => handleClick(attributes.slug)}
        >
          <ListItemText primary={attributes.titre} secondary={niAwtis ? new Intl.ListFormat('fr').format(attributes.artistes.data.map(({attributes}) => attributes.alias)) : null} />
          {attributes.explicite && (
            <ExplicitIcon style={{marginRight: 5}} color='secondary' />
          )}
          {attributes.okiMizikID && (
            <LibraryMusicIcon style={{fontSize: 40}} color='primary' />
          )}
          {esBrandNew(attributes.publishedAt) && (
            <FiberNewOutlinedIcon style={{fontSize: 40}} color='primary' />
          )}
        </ListItem>
      ))}
    </StyledList>
  )
}

MizikLis.propTypes = {
  meteEsMobilOuve: PropTypes.func,
  niAwtis: PropTypes.bool,
  paroles: PropTypes.array.isRequired,
  slugTeksChwazi: PropTypes.string,
  meteSlugTeksChwazi: PropTypes.func
}

MizikLis.defaultProps = {
  meteEsMobilOuve: null,
  niAwtis: false,
  slugTeksChwazi: null,
  meteSlugTeksChwazi: null
}
