import PropTypes from 'prop-types'
import {uniqueId} from 'lodash'

import {useRef, useEffect} from 'react'
import {useTheme} from '@mui/material/styles'
import Dialog from '@mui/material/Dialog'
import DialogContent from '@mui/material/DialogContent'
import DialogTitle from '@mui/material/DialogTitle'
import useMediaQuery from '@mui/material/useMediaQuery'
import DialogActions from '@mui/material/DialogActions'
import Button from '@mui/material/Button'

export default function Diferans({id, ouveDiferans, meteOuveDiferans, difference}) {
  const theme = useTheme()
  const fullScreen = useMediaQuery(theme.breakpoints.down('md'))
  const handleClose = () => {
    meteOuveDiferans(null)
  }

  const descriptionElementRef = useRef(null)
  useEffect(() => {
    if (ouveDiferans) {
      const {current: descriptionElement} = descriptionElementRef
      if (descriptionElement !== null) {
        descriptionElement.focus()
      }
    }
  }, [ouveDiferans])

  return (
    <Dialog
      sx={{zIndex: 9999}}
      open={ouveDiferans === id}
      fullScreen={fullScreen}
      scroll='paper'
      aria-labelledby='légende des différences'
      aria-describedby='différences des modifications'
      onClose={handleClose}
    >
      <DialogTitle id='légende des différences'>
        <small style={{color: 'grey'}}>Aucune modification</small><br />
        <small style={{background: '#fadad7', color: '#b30000'}}>Suppression</small> <br />
        <small style={{background: '#eaf2c2', color: '#406619'}}>Ajout</small>

      </DialogTitle>
      <DialogContent dividers>
        {difference.map(part => {
          const color = part.added ? 'green' : (part.removed ? 'red' : 'grey')
          return (
            <span key={uniqueId()} style={{color, whiteSpace: 'pre-line'}}>
              {!part.added && !part.removed && (
                <span>{part.value}</span>
              )}

              {part.added && (
                <ins>{part.value}</ins>
              )}

              {part.removed && (
                <del>{part.value}</del>
              )}
            </span>
          )
        })}
      </DialogContent>
      <DialogActions>
        <Button color='primary' onClick={handleClose}>
          Fermer
        </Button>
      </DialogActions>
      <style jsx>
        {`
          del {
            text-decoration: none;
            color: #b30000;
            background: #fadad7;
          }
          ins {
            background: #eaf2c2;
            color: #406619;
            text-decoration: none;
          }
        `}
      </style>
    </Dialog>
  )
}

Diferans.propTypes = {
  id: PropTypes.number.isRequired,
  ouveDiferans: PropTypes.number,
  meteOuveDiferans: PropTypes.func.isRequired,
  difference: PropTypes.array.isRequired
}
