import { useContext } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Button } from 'antd'
import { ElectronContext } from '../context/ElectronContext'
import OpenInAppIcon from '../../Icons/OpenInAppIcon'
import OpenInBrowserIcon from '../../Icons/OpenInBrowserIcon'
import config from '../../../config'
import KeyboardShortcut from './KeyboardShortcut'

const WebAppSwitcher = () => {
  const { isElectron, openExternalUrl } = useContext(ElectronContext)
  const location = useLocation()
  const navigate = useNavigate()

  const getCurrentPath = () =>
    `${location.pathname}${location.search}${location.hash}`

  const handleClick = () => {
    const path = getCurrentPath()

    if (isElectron) {
      const url = window.location.protocol.startsWith('http')
        ? `${window.location.origin}${path}`
        : `${config.webAppUrl}${path}`

      openExternalUrl(url)
      return
    }

    const redirectType =
      import.meta.env.MODE === 'development' ? 'app-localhost' : 'app-scheme'
    const redirect =
      redirectType === 'app-localhost'
        ? `http://localhost:3500${path}`
        : `farmcontrol://app${path}`

    const params = new URLSearchParams({
      redirect,
      redirectType
    })

    navigate(`/applaunch?${params.toString()}`)
  }

  return (
    <KeyboardShortcut shortcut='alt+w' hint='ALT W' onTrigger={handleClick}>
      <Button
        icon={isElectron ? <OpenInBrowserIcon /> : <OpenInAppIcon />}
        type='text'
        style={{ marginTop: '4px' }}
        onClick={handleClick}
      />
    </KeyboardShortcut>
  )
}

export default WebAppSwitcher
