import PropTypes from 'prop-types'
import {format} from 'date-fns'
import {fr} from 'date-fns/locale'
import {styled} from '@mui/material/styles'

import {
  Typography,
  Divider,
  List,
  ListItemText
} from '@mui/material'

import {formatJsonString} from '../../lib/utils/format'

const PREFIX = 'komante-list'

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

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

  [`& .${classes.inline}`]: {
    display: 'inline'
  }
}))

export default function KomanteList({commentaires}) {
  return (
    <StyledList className={classes.root}>
      {commentaires.map(({id, attributes}) => (
        <div key={id}>
          <ListItemText
            primary={
              <Typography gutterBottom style={{textDecoration: 'underline'}} variant='body1'>
                <small>{attributes.user.data.attributes.username}</small>
              </Typography>
            }
          />
          <ListItemText
            primary={formatJsonString(attributes.contenu)}
            secondary={
              <Typography gutterBottom style={{marginBlock: 5, fontStyle: 'italic'}} variant='caption' display='block'>
                {format(new Date(attributes.datePublication), 'Pp', {locale: fr})}
              </Typography>
            }
          />
          <Divider style={{marginBottom: '1em'}} />
        </div>
      ))}
    </StyledList>
  )
}

KomanteList.propTypes = {
  commentaires: PropTypes.array.isRequired
}
