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, teks, slugTeksChwazi, meteSlugTeksChwazi}) {
  const router = useRouter()

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

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

    if (meteEsMobilOuve) {
      meteEsMobilOuve(false)
    }
  }

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

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

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