import React, {useEffect, useState} from 'react'
import Image from 'next/image'
import PropTypes from 'prop-types'
import {withStyles} from '@material-ui/core/styles'
import {Box, Button, Divider, Snackbar, useMediaQuery, Link, Dialog} from '@material-ui/core'
import MuiDialogTitle from '@material-ui/core/DialogTitle'
import MuiDialogContent from '@material-ui/core/DialogContent'
import IconButton from '@material-ui/core/IconButton'
import CloseIcon from '@material-ui/icons/Close'
import Typography from '@material-ui/core/Typography'
import MuiAlert from '@material-ui/lab/Alert'
import FileCopyIcon from '@material-ui/icons/FileCopy'
import AndroidIcon from '@material-ui/icons/Android'
import AppleIcon from '@material-ui/icons/Apple'
import GetAppIcon from '@material-ui/icons/GetApp'
import {Windows, Linux} from '@icons-pack/react-simple-icons'

import sessionMobile from '../../public/session-mobile-914x1024.png'
import sessionDesktop from '../../public/session-desktop-1024x549.png'
import QRCode from '../../public/sesyon-qr-code.png'

const sessionUrl = process.env.NEXT_PUBLIC_SESSION_URL || 'http://sesyon.o-k-i.net'

function Alert(props) {
  return <MuiAlert elevation={6} variant='filled' {...props} />
}

const styles = theme => ({
  root: {
    margin: 0,
    padding: theme.spacing(2)
  },
  closeButton: {
    position: 'absolute',
    right: theme.spacing(1),
    top: theme.spacing(1),
    color: theme.palette.grey[500]
  }
})

const DialogTitle = withStyles(styles)(props => {
  const {children, classes, onClose, ...other} = props
  return (
    <MuiDialogTitle disableTypography className={classes.root} {...other}>
      <Typography variant='h6'>{children}</Typography>
      {onClose ? (
        <IconButton aria-label='close' className={classes.closeButton} onClick={onClose}>
          <CloseIcon />
        </IconButton>
      ) : null}
    </MuiDialogTitle>
  )
})

const DialogContent = withStyles(theme => ({
  root: {
    padding: theme.spacing(2)
  }
}))(MuiDialogContent)

export default function SesyonDialog({ouve, handleFemen}) {
  const isMobile = useMediaQuery('(max-width:800px)')
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [ouveSnack, meteOuveSnack] = useState(false)

  const handleFemenSnack = (event, reason) => {
    if (reason === 'clickaway') {
      return
    }

    meteOuveSnack(false)
    setSuccess('')
    setError('')
  }

  const handleCopyUrl = () => {
    if (typeof window !== 'undefined') {
      navigator.clipboard.writeText(sessionUrl)
        .then(
          () => setSuccess('URL copiée avec succès'),
          () => setError('Error lors de la copie du lien')
        )
    }

    meteOuveSnack(false)
  }

  useEffect(() => {
    if (error || success) {
      meteOuveSnack(true)
    }
  }, [error, success, meteOuveSnack])

  return (
    <div>
      <Dialog aria-labelledby='customized-dialog-title' open={ouve} onClose={handleFemen}>
        <DialogTitle style={{textAlign: 'center'}} id='customized-dialog-title' onClose={handleFemen}>
          Groupe Session
        </DialogTitle>
        <DialogContent dividers>
          <Typography gutterBottom style={{textAlign: 'center', fontWeight: 'bold'}}>
            Télécharger Session
          </Typography>
          <Box style={{display: 'flex', flexDirection: 'column', justifyContent: 'space-between'}}>
            <Box style={{display: 'flex', justifyContent: 'space-around'}}>
              <Typography>
                Mobile
              </Typography>
              <Typography>
                Ordinateur
              </Typography>
            </Box>
            <Box style={{display: 'flex', justifyContent: 'space-around'}}>
              <Box>
                <Image
                  src={sessionMobile}
                  width={228}
                  height={256}
                  placeholder='blur'
                />
              </Box>
              <Divider flexItem orientation='vertical' />
              <Box style={{alignSelf: 'center'}}>
                <Image
                  src={sessionDesktop}
                  width={256}
                  height={137}
                  placeholder='blur'
                />
              </Box>
            </Box>
            <Box style={{display: 'flex', justifyContent: 'space-around'}}>
              <Box style={{display: 'flex', justifyContent: 'center'}}>
                <Link target='_blank' rel='noopener noreferrer' href='https://getsession.org/android'>
                  <IconButton title='Play Store' aria-label='adroid-playstore'>
                    <AndroidIcon fontSize={isMobile ? 'small' : 'large'} />
                  </IconButton>
                </Link>
                <Link target='_blank' rel='noopener noreferrer' href='https://getsession.org/iphone'>
                  <IconButton title='App Store' aria-label='apple-app-store'>
                    <AppleIcon fontSize={isMobile ? 'small' : 'large'} />
                  </IconButton>
                </Link>
                <Link target='_blank' rel='noopener noreferrer' href='https://github.com/oxen-io/session-android/releases'>
                  <IconButton title='APK' aria-label='adroid-apk'>
                    <GetAppIcon fontSize={isMobile ? 'small' : 'large'} />
                  </IconButton>
                </Link>
              </Box>
              <Box style={{display: 'flex', justifyContent: 'center'}}>
                <Link target='_blank' rel='noopener noreferrer' href='https://getsession.org/mac'>
                  <IconButton title='Mac' aria-label='mac'>
                    <AppleIcon fontSize={isMobile ? 'small' : 'large'} />
                  </IconButton>
                </Link>
                <Link target='_blank' rel='noopener noreferrer' href='https://getsession.org/windows'>
                  <IconButton title='Windows' aria-label='windows'>
                    <Windows size={isMobile ? 18 : 32} />
                  </IconButton>
                </Link>
                <Link target='_blank' rel='noopener noreferrer' href='https://getsession.org/linux'>
                  <IconButton title='Linux' aria-label='linux'>
                    <Linux size={isMobile ? 18 : 32} />
                  </IconButton>
                </Link>
              </Box>
            </Box>
          </Box>
          <Divider style={{marginBlock: '1em'}} />
          <Typography gutterBottom style={{textAlign: 'center', fontWeight: 'bold'}}>
            Rejoindre le groupe public
          </Typography>
          <Box style={{textAlign: 'center'}}>
            <Image
              src={QRCode}
              width={200}
              height={200}
              placeholder='blur'
            />
          </Box>
          <Box style={{textAlign: 'center', marginBlock: 20}}>
            <Button
              variant='contained'
              color='primary'
              startIcon={<FileCopyIcon />}
              onClick={handleCopyUrl}
            >
              Copier l’URL du groupe
            </Button>
          </Box>
        </DialogContent>
      </Dialog>
      {success && (
        <Snackbar open={ouveSnack} autoHideDuration={3000} onClose={handleFemenSnack}>
          <Alert severity='success' onClose={handleFemenSnack}>
            <strong>{success}</strong>
          </Alert>
        </Snackbar>
      )}
      {error && (
        <Snackbar open={ouveSnack} autoHideDuration={3000} onClose={handleFemenSnack}>
          <Alert severity='error' onClose={handleFemenSnack}>
            <strong>Une erreur s’est produite</strong> : <i>{error.message}</i>
          </Alert>
        </Snackbar>
      )}
    </div>
  )
}

SesyonDialog.propTypes = {
  ouve: PropTypes.bool.isRequired,
  handleFemen: PropTypes.func.isRequired
}
