import React from 'react'
import PropTypes from 'prop-types'
import {Button, Dialog, DialogActions, DialogContent, DialogTitle, makeStyles, Typography} from '@material-ui/core'
import Cgu from '.'
import {useRouter} from 'next/router'

const CGU_DOWNLOAD_LINK = process.env.NEXT_PUBLIC_CGU_DOWNLOAD_LINK

const useStyles = makeStyles(() => ({
  dialog: {
    zIndex: 9999
  }
}))

export default function CGUDialog({open, setOpen}) {
  const classes = useStyles()
  const router = useRouter()

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

  const handleClick = event => {
    event.preventDefault()
    router.push(CGU_DOWNLOAD_LINK)
  }

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

  return (
    <div>
      <Dialog
        open={open}
        scroll='paper'
        aria-labelledby='scroll-dialog-title'
        aria-describedby='scroll-dialog-description'
        className={classes.dialog}
        onClose={handleClose}
      >
        <DialogTitle id='scroll-dialog-title'>CGU et politique de confidentialité</DialogTitle>
        <DialogContent dividers>
          <Typography
            ref={descriptionElementRef}
            variant='inherit'
            id='scroll-dialog-description'
            tabIndex={-1}
          >
            <Cgu />
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button color='primary' onClick={handleClick}>
            Voir au format pdf
          </Button>
          <Button color='primary' onClick={handleClose}>
            Fermer
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  )
}

CGUDialog.propTypes = {
  open: PropTypes.bool.isRequired,
  setOpen: PropTypes.func.isRequired
}
