import React, { useState, useEffect } from 'react'
import { detectOS, isAppleSilicon } from '../../helpers/utils'
import { getClientDownloads } from '../../helpers/rest'
import { Link } from 'react-router-dom'
const DownloadButtonWindowsLegacy = '/img/downloads/Download-Button-Windows-Legacy.svg'
const DownloadButtonMacLegacy = '/img/downloads/Download-Button-Mac-Legacy.svg'

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

  const availablePlatforms = React.useMemo(() => {
    const keys = Object.keys(downloads)
    //only show JamClientModern versions
    const sortedStrings = keys.filter(key => ['JamClient/Win32', 'JamClient/MacOSX'].includes(key)).map(key => key.substring('JamClient/'.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 = () => {
    getClientDownloads()
      .then(resp => {
        if (resp.status === 200) {
          return resp.json()
        }
      }).then(data => {
        const platforms = Object.keys(data)
        const downloadUris = {}
        platforms.filter(p => p === 'JamClient/MacOSX' || p === 'JamClient/Win32').forEach(platform => {
          downloadUris[platform] = data[platform].uri
        })
        setDownloads(downloadUris)
        detectAndSetOS()
      })
      .catch(err => {
        console.error(err)
      })
  }

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

  useEffect(() => {
    if (currentOS) {
      if(isMacOS){
        selectPlatform('MacOSX')
      }else if(isWindows){
        selectPlatform('Win32')
      }
    }
  }, [currentOS])

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

  const selectPlatform = (platform) => {
    setSelectedPlatform(platform)
  }

  const downloadImageUrl = React.useMemo(() => {
    if (!selectedPlatform) return null
    if(selectedPlatform === 'MacOSX'){
      return DownloadButtonMacLegacy
    }else if(selectedPlatform === 'Win32'){
      return DownloadButtonWindowsLegacy
    }
  }, [selectedPlatform])

  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':
        return 'JamKazam for Mac (Legacy)'
      case 'Win32':
        return 'JamKazam for Windows (Legacy)'
    }
  }

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

  return (
    <>
      {Object.keys(downloads).length > 0 && currentOS ? (
        <div>
          <h5>Download the older legacy JamKazam app</h5>
          {/* <p>{currentOS}</p>
          <p>{selectedPlatform}</p> */}
          <p className="mb-lg-4">
            You must use the JamKazam app to get into online sessions with other musicians. Our app also gives you the most feature-rich experience for JamTracks, recordings, live broadcasting, and other features. Click the button below to download the JamKazam app installer, then double click the installer to run it. For more detailed instructions,&nbsp;
            {isMacOS ? <a href="https://jamkazam.freshdesk.com/support/solutions/articles/66000130025" target="_blank">see this help article</a> : isWindows && <a href="https://jamkazam.freshdesk.com/support/solutions/articles/66000130024" target="_blank">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' style={ { cursor: 'pointer' } }>
                <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 !== selectedPlatform).map(platform => (
                  <li key={platform}><a href="#" onClick={(e) => onClickPlatform(e, platform)}>{platformDisplayName(platform)}</a></li>
                ))}
                <li>
                  <Link to="/public/downloads">Download page for current app version</Link>
                </li>
              </ul>
            </div>
          </div>
          <div className='mt-lg-4'>
            <div><strong>System Requirements</strong></div>
            {selectedPlatform === 'MacOSX' ? (
              <p>
                To play an online session on JamKazam, you will need the following:<br />
                - macOS 10.8 (Mountain Lion) or higher <br />
                - 75MB hard disk space for app installation <br />
                - External audio interface for audio processing (<a href="https://jamkazam.freshdesk.com/support/solutions/articles/66000122513" target='_blank'>see recommendations if you don't have one</a>) <br />
                - Ability to connect computer to home router using Ethernet cable. WiFi not recommended (<a href='https://jamkazam.freshdesk.com/support/solutions/articles/66000124756' target='_blank'>learn how to do this</a>) <br />
                - Broadband internet service with at least 1Mbps download and upload bandwidth (3-5Mbps preferred) <br />
                - Note that the audio interface and Ethernet links to same places as other Mac links above
              </p>
            ) : selectedPlatform === 'Win32' ? (
              <p>
                To play an online session on JamKazam, you will need the following:<br />
                - Windows 7, 32-bit or 64-bit <br />
                - Dual core processor or higher <br />
                - 75MB hard disk space for app installation <br />
                - External audio interface for audio processing (<a href='https://jamkazam.freshdesk.com/support/solutions/articles/66000122514' target='_blank'>see recommendations if you don't have one</a>) <br />
                - Ability to connect computer to home router using Ethernet cable, WiFi not recommended (<a href="https://jamkazam.freshdesk.com/support/solutions/articles/66000124756" target='_blank'>learn how to do this</a>) <br />
                - Broadband Internet service with at least 1Mbps download and upload bandwidth (3-5Mbps preferred)
                - Note that the audio interface and Ethernet links to same places as other Windows links above
              </p>
            ) : null}

          </div>


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

export default JKDownloadsLegacy