import {useRef, useEffect} from 'react'
import {styled} from '@mui/material/styles'
import PropTypes from 'prop-types'
import {Button, Dialog, DialogActions, DialogContent, DialogTitle, Typography} from '@mui/material'
import {useRouter} from 'next/router'
import Cgu from '.'

const PREFIX = 'cgu-dialog'

const classes = {
  dialog: `${PREFIX}-dialog`
}

const Root = styled('div')(() => ({
  [`& .${classes.dialog}`]: {
    zIndex: 9999
  }
}))

const CGU_DOWNLOAD_LINK = process.env.NEXT_PUBLIC_CGU_DOWNLOAD_LINK

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

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

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

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

  return (
    <Root>
      <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>
    </Root>
  )
}

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