import React, { useState, useEffect } from 'react'
import { detectOS, isAppleSilicon } from '../../helpers/utils'
import {getClientDownloads, getObsPluginDownloads} from '../../helpers/rest'
import { Link } from 'react-router-dom'

const DownloadButtonMacAppleMx = '/img/downloads/Download-Button-Obs-Mac-Apple-Mx.png'
const DownloadButtonMacIntel = '/img/downloads/Download-Button-Obs-Mac-Intel.png'
const DownloadButtonWindows = '/img/downloads/Download-Button-Obs-Windows.png'

const JKObsDownloads = () => {
  const [currentOS, setCurrentOS] = useState(null)
  const [downloads, setDownloads] = useState({})

  const availablePlatforms = React.useMemo(() => {
    const keys = Object.keys(downloads)
    //only show JamClientModern versions
    const sortedStrings = keys.filter(key => key.startsWith('OBSPlugin')).map(key => key.substring('OBSPlugin/'.length))

    return sortedStrings
  }, [downloads])

  const detectAndSetOS = () => {
    let os = detectOS()

    if (os == "MacOSX") {
      const silicon = isAppleSilicon();
      if (silicon == true) {
        os = "MacOSX-M";
      }
      else {
        os = "MacOSX-Intel";
      }
    }
    if (!os) {
      os = "Win32"
    }
    setCurrentOS(os)
  }

  const fetchClientDownloads = () => {
    getObsPluginDownloads()
      .then(resp => {
        if (resp.status === 200) {
          return resp.json()
        }
      }).then(data => {
        const platforms = Object.keys(data)
        const downloadUris = {}
        platforms.filter(p => p === 'OBSPlugin/MacOSX-M' || p === 'OBSPlugin/MacOSX-Intel' || p === 'OBSPlugin/Win32').forEach(platform => {
          downloadUris[platform] = data[platform].uri
        })
        setDownloads(downloadUris)
        detectAndSetOS()
      })
      .catch(err => {
        console.error(err)
      })
  }

  useEffect(() => {
    fetchClientDownloads()
  }, [])

  const downloadLink = React.useMemo(() => {
    if (!currentOS) return null
    return downloads[`OBSPlugin/${currentOS}`]
  }, [currentOS]);

  const selectPlatform = (platform) => {
    console.log('_DEBUG_ platform', platform)
    setCurrentOS(platform)
  }

  const downloadImageUrl = React.useMemo(() => {
    if (!currentOS) return null
    switch (currentOS) {
      case 'MacOSX-M':
        return DownloadButtonMacAppleMx
      case 'MacOSX-Intel':
        return DownloadButtonMacIntel
      case 'Win32':
        return DownloadButtonWindows
    }
  }, [currentOS])

  const isMacOS = React.useMemo(() => {
    if (!currentOS) return false
    return currentOS.startsWith('MacOSX')
  }, [currentOS])


  const isWindows = React.useMemo(() => {
    if (!currentOS) return false
    return currentOS === 'Win32'
  }, [currentOS])

  const platformDisplayName = (platform) => {
    switch (platform) {
      case 'MacOSX-M':
        return 'JamKazam for Mac (Apple Silicon)'
      case 'MacOSX-Intel':
        return 'JamKazam for Mac (Intel)'
      case 'Win32':
        return 'JamKazam for Windows'
    }
  }

  const onClickPlatform = (event, platform) => {
    event.preventDefault()
    selectPlatform(platform)
  }

  return (
    <>
      {Object.keys(downloads).length > 0 && currentOS ? (
        <div>
          <h5>Download and install OBS Studio</h5>
          {/* <p>{currentOS}</p> */}
          <p>

Before installing the JamKazam plugin for OBS, you must first download and install OBS Studio.
            If you have not already done so, <a target="_blank" href="https://jamkazam.freshdesk.com/support/solutions/articles/66000525817">follow the instructions in this help article</a> to download
            and install OBS Studio version 30.2.3. Please note that you cannot use OBS video features with the legacy
            JamKazam application - only with the current version of our app.
          </p>
          <h5 className="mt-lg-4">Download and install JamKazam plugin for OBS</h5>
          <p  className="mb-lg-4">
            After installing OBS Studio as explained above, you'll need to install the JamKazam
            plugin for OBS. This plugin lets JamKazam and OBS Studio work together. Click the button
            below to download the plugin installer. When the download is complete, double click the
            installer, and then follow the on-screen instructions to install the plugin. For more detailed
            instructions, <a target="_blank"  href="https://jamkazam.freshdesk.com/support/solutions/articles/66000525817">see this help article</a>.
          </p>
          <div className='mt-2 d-flex flex-column flex-md-row'>
            <div style={ { flexGrow: 0, flexShrink: 0, flexBasis: '25%' } }>
              <a href={downloadLink} target='_blank'>
                <img src={downloadImageUrl} alt="Download JamKazam" />
              </a>
            </div>
            <div className='mt-3 mt-lg-0 ml-lg-5' style={ { flexGrow: 1, flexShrink: 1, flexBasis: '75%' } }>
              <div>Need a different version?</div>
              <ul className='list-unstyled'>
                {availablePlatforms.filter(platform => platform !== currentOS).map(platform => (
                  <li key={platform}><a href="#" onClick={(e) => onClickPlatform(e, platform)}>{platformDisplayName(platform)}</a></li>
                ))}
              </ul>
            </div>
          </div>
          <div className='mt-lg-4'>
            <h5>System Requirements</h5>
            {isMacOS ? (
              <p>
                To install the JamKazam plugin for OBS Studio:<br />
                - OBS Studio version 30.2.3 must already be installed on your computer <br />
                - Your Mac must be running macOS 10.15 (Catalina) or higher <br />
              </p>
            ) : isWindows ? (
              <p>
                To install the JamKazam plugin for OBS Studio<br />
                - OBS Studio version 30.2.3 must already be installed on your computer <br />
                - Your computer must be running Windows 10 or 11, 64-bit (32-bit not supported)
              </p>
            ) : null}

          </div>
        </div>
      ) : (
        <div>Loading...</div>
      )}
    </>
  )
}

export default JKObsDownloads