'use client'

import {useState} from 'react'
import PropTypes from 'prop-types'

import {styled} from '@mui/material/styles'
import SpeedDial from '@mui/material/SpeedDial'
import SpeedDialIcon from '@mui/material/SpeedDialIcon'
import SpeedDialAction from '@mui/material/SpeedDialAction'
import FileCopyIcon from '@mui/icons-material/FileCopyOutlined'
import ShareIcon from '@mui/icons-material/Share'
import TwitterIcon from '@mui/icons-material/Twitter'
import TelegramIcon from '@mui/icons-material/Telegram'
import FacebookIcon from '@mui/icons-material/Facebook'
import WhatsAppIcon from '@mui/icons-material/WhatsApp'
import {Backdrop} from '@mui/material'

const twitterUrl = 'https://twitter.com/intent/tweet'
const telegramUrl = 'https://telegram.me/share/url'
const facebookUrl = 'https://www.facebook.com/sharer/sharer.php'
const whatsappUrl = 'whatsapp://send'

const PREFIX = 'pataje'

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

const Root = styled('div')(() => ({
  [`&.${classes.root}`]: {
    height: 0,
    transform: 'translateZ(0px)'
  }
}))

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL
const TWITTER_HASHTAGS = process.env.NEXT_PUBLIC_TWITTER_HASHTAGS || 'OKi'
const TWITTER_USERNAME = process.env.NEXT_PUBLIC_TWITTER_USERNAME || 'OrganisationKA'

const actions = [
  {icon: <WhatsAppIcon />, name: 'WhatsApp', code: 'whatsapp'},
  {icon: <FacebookIcon />, name: 'Facebook', code: 'facebook'},
  {icon: <TwitterIcon />, name: 'Twitter', code: 'twitter'},
  {icon: <TelegramIcon />, name: 'Telegram', code: 'telegram'},
  {icon: <FileCopyIcon />, name: 'Copier le lien', code: 'copy'}
]

export default function Pataje({parole, setError, setSuccess}) {
  const {titre, artistes, slug} = parole
  const [open, setOpen] = useState(false)

  const patajeUrl = `${SITE_URL}/paroles/${slug}`
  const alias = artistes.map(({alias}) => alias)
  const renderAwtis = new Intl.ListFormat('fr').format(alias)

  const text = parole.user || parole.userAdmin ? `${renderAwtis} - ${titre} (Paroles et Traductions) - (parole soumise par ${parole?.user?.username || parole.userAdmin?.username || parole.userAdmin?.firstname})` : `${renderAwtis} - ${titre} (Paroles et Traductions)`

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

  const handleOpen = () => {
    setOpen(true)
  }

  const handleClick = code => {
    if (typeof window !== 'undefined') {
      switch (code) {
        case 'whatsapp':
          window.open(`${whatsappUrl}?text=${encodeURI(text)} \n ${encodeURI(patajeUrl)}`, '_blank')
          break

        case 'facebook':
          window.open(`${facebookUrl}?u=${encodeURI(patajeUrl)}`, '_blank')
          break

        case 'telegram':
          window.open(`${telegramUrl}?url=${encodeURI(patajeUrl)}&text=${encodeURI(text)}`, '_blank')
          break

        case 'twitter':
          window.open(`${twitterUrl}?hashtags=${TWITTER_HASHTAGS}&text=${text}&via=${TWITTER_USERNAME}&url=${patajeUrl}`, 'Partage Twitter', 'width=600,height=300')
          break

        case 'copy':
          navigator.clipboard.writeText(patajeUrl)
            .then(
              () => setSuccess('Lien copié avec succès'),
              () => setError('Error lors de la copie du lien')
            )
          break

        default:
          break
      }
    }

    setOpen(false)
  }

  return (
    <Root className={classes.root}>
      <Backdrop open={open} />
      <SpeedDial
        FabProps={{size: 'small', color: 'secondary'}}
        ariaLabel='Patajé'
        icon={<SpeedDialIcon icon={<ShareIcon />} />}
        open={open}
        direction='down'
        onClose={handleClose}
        onOpen={handleOpen}
      >
        {actions.map(action => (
          <SpeedDialAction
            key={action.name}
            icon={action.icon}
            placement='right'
            title={action.name}
            onClick={() => handleClick(action.code)}
          />
        ))}
      </SpeedDial>
    </Root>
  )
}

Pataje.propTypes = {
  parole: PropTypes.object.isRequired,
  setError: PropTypes.func.isRequired,
  setSuccess: PropTypes.func.isRequired
}
