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 '@material-ui/core'
import ExplicitIcon from '@material-ui/icons/Explicit'
import {makeStyles} from '@material-ui/core/styles'

const useStyles = makeStyles({
  root: {
    maxWidth: 345
  },
  media: {
    height: 240,
    objectFit: 'contain'
  }
})

export default function TeksKat({teks}) {
  const classes = useStyles()
  const router = useRouter()
  const noImageUrl = 'https://place-hold.it/140x140?text=Pa%20ni%20imaj'
  const {tit, awtis, lanne, kouveti, published_at, slug} = teks
  const datPiblikasyon = format(new Date(published_at), 'P', {locale: fr})

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

  return (
    <Grid item sm={12} md={6} lg={4}>
      <Card className={classes.root}>
        <CardActionArea onClick={() => handleClick(slug)}>
          <CardMedia
            className={classes.media}
            component='img'
            alt={tit}
            image={kouveti ? `${process.env.NEXT_PUBLIC_API_URL}${kouveti.url}` : noImageUrl}
            title={tit}
          />
          <CardContent>
            <Typography display='inline' style={{marginRight: 5}} variant='h6' component='h2'>
              {tit}
            </Typography>
            {teks.eksplisit && (
              <ExplicitIcon style={{marginRight: 5}} color='secondary' fontSize='small' />
            )}
            <Typography variant='caption'>
              {teks.user && (
                <>
                  (<i>texte soumis par {teks.user.username}</i>)
                </>
              )}
            </Typography>
            <Typography variant='body2' color='textSecondary' component='p'>
              {awtis.map(a => a.alias).join(', ')}
            </Typography>
            <Typography variant='body2' color='textSecondary' component='p'>
              {lanne}
            </Typography>
            <Typography align='center' style={{marginTop: '0.5em'}} variant='body1' color='textSecondary' component='p'>
              Piblikasyon : {datPiblikasyon}
            </Typography>
          </CardContent>
        </CardActionArea>
      </Card>
    </Grid>
  )
}

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