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

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

const JKDownloads = () => {
  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('JamClientModern') && key !== 'MacOSX').map(key => key.substring('JamClientModern/'.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 === 'JamClientModern/MacOSX-M' || p === 'JamClientModern/MacOSX-Intel' || p === 'JamClientModern/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[`JamClientModern/${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 the free JamKazam app</h5>
          {/* <p>{currentOS}</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 !== currentOS).map(platform => (
                  <li key={platform}><a href="#" onClick={(e) => onClickPlatform(e, platform)}>{platformDisplayName(platform)}</a></li>
                ))}
              </ul>
            </div>
          </div>
          <div className='mt-1 mt-lg-4'>
            <div><strong>System Requirements</strong></div>
            {isMacOS ? (
              <p>
                To play an online session on JamKazam, you will need the following:<br />
                - macOS 10.15 (Catalina) 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 />
              </p>
            ) : isWindows ? (
              <p>
                To play an online session on JamKazam, you will need the following:<br />
                - Windows 10 or 11, 64-bit (32-bit not supported) <br />
                - Dual core processor or higher (quad or higher preferred) <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)
              </p>
            ) : null}

          </div>

          {isMacOS ? (
            <div>
              <div><strong>Instructions for Users With Older Macs</strong></div>
              <p>
                If your Mac cannot support macOS 10.15 (Catalina) or higher, you can still play with everyone else on JamKazam using our legacy app. To do this, <Link to="/public/downloads-legacy">click here</Link> to go to a page where you can download JamKazam legacy app for older Macs. Download and install legacy app on your computer. Then <a href="https://jamkazam.freshdesk.com/support/solutions/articles/66000526271" target='_blank'>read this help article</a> about how to use the legacy app.
              </p>
            </div>
          ) : isWindows ? (
            <div>
              <div><strong>Instructions for Users With Older Windows PCs</strong></div>
              <p>
                If your Windows computer cannot support Win10 or Win11, you can still play with everyone else on JamKazam using our legacy app. To do this <Link to="/public/downloads-legacy">click here</Link> to go to a page where you can download the JamKazam legacy app for older Windows PCs. Download and install the legacy app on your Win7 computer. Then <a href="https://jamkazam.freshdesk.com/support/solutions/articles/66000526271" target='_blank'>read this help article</a> about how to use the legacy app.
              </p>
            </div>
          ) : null}


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

export default JKDownloads