import React, {forwardRef, useState} from 'react'
import PropTypes from 'prop-types'

import {format} from 'date-fns'
import {fr} from 'date-fns/locale'

import Button from '@mui/material/Button'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import Box from '@mui/material/Box'
import Slide from '@mui/material/Slide'
import List from '@mui/material/List'
import ListItemButton from '@mui/material/ListItemButton'
import ListItemText from '@mui/material/ListItemText'
import ListItemAvatar from '@mui/material/ListItemAvatar'
import Avatar from '@mui/material/Avatar'
import LyricsIcon from '@mui/icons-material/Lyrics'

import Diferans from './diferans'

const Transition = forwardRef(function Transition(props, ref) {
  return <Slide ref={ref} direction='up' {...props} />
})

export default function DiferansDialog({difference}) {
  const [ouve, meteOuve] = useState(false)
  const [ouveDiferans, meteOuveDiferans] = useState(null)

  const handleClickOpen = () => {
    meteOuve(true)
  }

  const handleClose = () => {
    meteOuve(false)
  }

  return (
    <Box sx={{textAlign: 'center', marginTop: 2}}>
      <Button variant='outlined' onClick={handleClickOpen}>
        Voir la liste des modifications
      </Button>
      <Dialog
        keepMounted
        open={ouve}
        TransitionComponent={Transition}
        aria-describedby='liste des modifications'
        onClose={handleClose}
      >
        <DialogTitle>Liste des modifications</DialogTitle>
        <List sx={{width: '100%', maxWidth: 360, bgcolor: 'background.paper'}}>
          {difference.map(({id, admin_user, date, jsonDiff}) => {
            const {firstname} = admin_user
            const diferansDate = format(new Date(date), 'PPPppp', {locale: fr})

            return (
              <React.Fragment key={id}>
                <ListItemButton
                  onClick={() => meteOuveDiferans(id)}
                >
                  <ListItemAvatar>
                    <Avatar>
                      <LyricsIcon />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText primary={`Modifié par : ${firstname}`} secondary={diferansDate} />
                </ListItemButton>
                <Diferans id={id} ouveDiferans={ouveDiferans} meteOuveDiferans={meteOuveDiferans} difference={jsonDiff} />
              </React.Fragment>
            )
          })}
        </List>
      </Dialog>
    </Box>
  )
}

DiferansDialog.propTypes = {
  difference: PropTypes.array.isRequired
}

