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

const PREFIX = 'cgu-dialog'

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

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

const CGU_DOWNLOAD_LINK = process.env.NEXT_PUBLIC_CGU_DOWNLOAD_LINK

export default function CGUDialog({open, setOpen}) {
  const theme = useTheme()
  const fullScreen = useMediaQuery(theme.breakpoints.down('md'))

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

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

  return (
    <Root>
      <Dialog
        fullScreen={fullScreen}
        open={open}
        scroll='paper'
        aria-labelledby='scroll-dialog-title'
        aria-describedby='scroll-dialog-description'
        className={classes.dialog}
        onClose={handleClose}
      >
        <DialogTitle className={classes.dialog} id='scroll-dialog-title'>CGU et politique de confidentialité</DialogTitle>
        <DialogContent dividers>
          <Typography
            ref={descriptionElementRef}
            component='div'
            variant='inherit'
            id='scroll-dialog-description'
            tabIndex={-1}
          >
            {CGU_DOWNLOAD_LINK ? (
              <div style={{textAlign: 'center', padding: '2rem'}}>
                <Typography paragraph>
                  Consultez nos CGU et notre politique de confidentialité :
                </Typography>
                <Button
                  variant='contained'
                  component='a'
                  href={CGU_DOWNLOAD_LINK}
                  target='_blank'
                  rel='noopener noreferrer'
                >
                  Consulter les CGU
                </Button>
              </div>
            ) : (
              <Cgu />
            )}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button color='primary' onClick={handleClose}>
            Fermer
          </Button>
        </DialogActions>
      </Dialog>
    </Root>
  )
}

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