import PropTypes from 'prop-types'
import {useRouter} from 'next/router'
import {format} from 'date-fns'
import {fr} from 'date-fns/locale'
import {
  Card,
  CardActionArea,
  CardContent,
  CardMedia,
  Typography,
  Grid
} from '@mui/material'
import ExplicitIcon from '@mui/icons-material/Explicit'
import {styled} from '@mui/material/styles'

const PREFIX = 'teks-kat'
const IMAGE_URL = process.env.NEXT_PUBLIC_API_URL_ROOT || 'http://localhost:1337'

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

const StyledGrid = styled(Grid)({
  [`& .${classes.root}`]: {
    maxWidth: 345
  },
  [`& .${classes.media}`]: {
    height: 240,
    objectFit: 'contain'
  }
})

const noImageUrl = 'https://place-hold.it/140x140?text=Indisponible'

export default function TeksKat({parole}) {
  const router = useRouter()
  const {attributes} = parole
  const {titre, artistes, annee, couverture, publishedAt, slug} = attributes

  const datPiblikasyon = format(new Date(publishedAt), 'P', {locale: fr})
  const alias = artistes.data.map(({attributes}) => attributes.alias)

  const handleClick = slug => {
    router.push(`/paroles/${slug}#${slug}`).then(() => window.scrollTo(0, 0))
  }

  return (
    <StyledGrid item xs={12} sm={6} md={4}>
      <Card className={classes.root}>
        <CardActionArea onClick={() => handleClick(slug)}>
          <CardMedia
            className={classes.media}
            component='img'
            alt={titre}
            image={couverture?.data?.attributes?.url ? `${IMAGE_URL}${couverture.data.attributes.url}` : noImageUrl}
            title={titre}
          />
          <CardContent>
            <Typography display='inline' style={{marginRight: 5}} variant='h6' component='h2'>
              {titre}
            </Typography>
            {parole.eksplisit && (
              <ExplicitIcon style={{marginRight: 5}} color='secondary' fontSize='small' />
            )}
            <Typography variant='caption'>
              {parole.user && (
                <>
                  (<i>texte soumis par {parole.user.username}</i>)
                </>
              )}
              {parole.userAdmin && !parole.user && (
                <>
                  (<i>texte soumis par {parole.userAdmin}</i>)
                </>
              )}
            </Typography>
            <Typography variant='body2' color='textSecondary' component='p'>
              {new Intl.ListFormat('fr').format(alias)}
            </Typography>
            <Typography variant='body2' color='textSecondary' component='p'>
              {annee}
            </Typography>
            <Typography align='center' style={{marginTop: '0.5em'}} variant='body1' color='textSecondary' component='p'>
              Publié le : {datPiblikasyon}
            </Typography>
          </CardContent>
        </CardActionArea>
      </Card>
    </StyledGrid>
  )
}

TeksKat.propTypes = {
  parole: PropTypes.object.isRequired
}
