import { useContext, useEffect, useState } from 'react'
import {
  Flex,
  Typography,
  Button,
  Dropdown,
  Skeleton,
  Tag,
  Divider
} from 'antd'
import useCollapseState from '../hooks/useCollapseState'
import InfoCollapse from '../common/InfoCollapse'
import InfoCircleIcon from '../../Icons/InfoCircleIcon'
import ReloadIcon from '../../Icons/ReloadIcon'
import DownloadIcon from '../../Icons/DownloadIcon'
import DeveloperIcon from '../../Icons/DeveloperIcon'
import { version as appVersion } from '../../../../package.json'
import { ApiServerContext } from '../context/ApiServerContext'
import { AuthContext } from '../context/AuthContext'
import { ElectronContext } from '../context/ElectronContext'
import { AppUpdateContext } from '../context/AppUpdateContext'
import { useMediaQuery } from 'react-responsive'
import FarmControlAppIcon from '../../Logos/FarmControlAppIcon'
const { Title, Text, Link } = Typography

const About = () => {
  const [collapseState, updateCollapseState] = useCollapseState('About', {
    updater: true
  })
  const { token } = useContext(AuthContext)
  const { fetchApiServerVersion, fetchWsServerVersion } =
    useContext(ApiServerContext)
  const { isElectron, getElectronVersion } = useContext(ElectronContext)
  const { checkForUpdates } = useContext(AppUpdateContext)
  const isMobile = useMediaQuery({ maxWidth: 768 })

  const buildNumber = import.meta.env.VITE_BUILD_NUMBER
    ? 'b' + import.meta.env.VITE_BUILD_NUMBER
    : 'dev'
  const developmentMode = import.meta.env.MODE === 'development'

  const actions = [
    {
      label: 'Reload Window',
      icon: <ReloadIcon />,
      onClick: () => {
        window.location.reload()
      }
    }
  ]

  if (isElectron) {
    actions.unshift(
      {
        label: 'Check for Updates',
        icon: <DownloadIcon />,
        onClick: checkForUpdates
      },
      { type: 'divider' }
    )
  }

  useEffect(() => {
    if (token) {
      fetchApiServerVersion().then((version) => {
        setApiServerVersion(version)
      })
      fetchWsServerVersion().then((version) => {
        setWsServerVersion(version)
      })
    }
  }, [fetchApiServerVersion, fetchWsServerVersion, token])

  useEffect(() => {
    if (!isElectron) return

    getElectronVersion()
      .then((version) => {
        setElectronVersion(version || 'unknown')
      })
      .catch(() => {
        setElectronVersion('unknown')
      })
  }, [getElectronVersion, isElectron])

  const [apiServerVersion, setApiServerVersion] = useState(null)
  const [wsServerVersion, setWsServerVersion] = useState(null)
  const [electronVersion, setElectronVersion] = useState(null)

  const apiServerVersionText = apiServerVersion ? (
    <Text>
      {`v${apiServerVersion.version}-${apiServerVersion.buildNumber == 'dev' ? 'dev' : 'b' + apiServerVersion.buildNumber}`}
    </Text>
  ) : (
    <Skeleton.Input active size='small' className='text-skeleton' />
  )
  const wsServerVersionText = wsServerVersion ? (
    <Text>{`v${wsServerVersion.version}-${wsServerVersion.buildNumber == 'dev' ? 'dev' : 'b' + wsServerVersion.buildNumber}`}</Text>
  ) : (
    <Skeleton.Input active size='small' className='text-skeleton' />
  )
  const electronVersionText = electronVersion ? (
    <Text>{`v${electronVersion}`}</Text>
  ) : (
    <Skeleton.Input active size='small' className='text-skeleton' />
  )

  return (
    <div style={{ height: '100%', minHeight: 0, overflowY: 'auto' }}>
      <Flex vertical gap='large'>
        <Flex vertical gap='middle' align='start'>
          <Dropdown menu={{ items: actions }}>
            <Button>Actions</Button>
          </Dropdown>
        </Flex>
        <Flex vertical gap='large'>
          <InfoCollapse
            title='About Farm Control'
            icon={<InfoCircleIcon />}
            canCollapse={false}
            active={collapseState.purchaseOrderStats}
            onToggle={(isActive) =>
              updateCollapseState('purchaseOrderStats', isActive)
            }
            className='no-t-padding-collapse'
            collapseKey='purchaseOrderStats'
          >
            <Flex gap='large'>
              <FarmControlAppIcon
                style={{ width: '200px', height: '200px' }}
              />
              <Flex vertical gap='small' justify='center'>
                <Flex gap='middle' align='center'>
                  <Title level={2} style={{ margin: 0 }}>
                    Farm Control
                  </Title>
                  {developmentMode && !isMobile && (
                    <Tag
                      color='yellow'
                      style={{ marginRight: 0 }}
                      icon={<DeveloperIcon />}
                    >
                      Development
                    </Tag>
                  )}
                </Flex>
                <Text type='secondary'>
                  3D Printer ERP and Control Software.
                </Text>
                <Flex style={{ columnGap: '15px', rowGap: '8px' }} wrap='wrap'>
                  <Text type='secondary'>
                    User Interface:{' '}
                    <Text>
                      v{appVersion}-{buildNumber}
                    </Text>
                  </Text>
                  {isElectron && (
                    <Text type='secondary'>
                      Electron: {electronVersionText}
                    </Text>
                  )}

                  <Text type='secondary'>REST API: {apiServerVersionText}</Text>
                  <Text type='secondary'>
                    Web Socket: {wsServerVersionText}
                  </Text>
                </Flex>
                <Flex gap='middle' align='center'>
                  {developmentMode && isMobile && (
                    <Tag
                      color='yellow'
                      style={{ marginRight: 0 }}
                      icon={<DeveloperIcon />}
                    >
                      Development
                    </Tag>
                  )}
                  <Link href='https://ci.tombutcher.work/job/farmcontrol'>
                    Jenkins
                  </Link>
                  <Divider type='vertical' style={{ margin: 0 }} />
                  <Link href='https://github.com/farmcontrol'>GitHub</Link>
                </Flex>
              </Flex>
            </Flex>
          </InfoCollapse>
        </Flex>
      </Flex>
    </div>
  )
}

export default About
