import { ReloadOutlined } from '@ant-design/icons'
import { Button, Descriptions, Popconfirm, Switch, Statistic } from 'antd'
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'

import {
  getDashboardStats,
  getSystemSettings,
  updateSystemSettings
} from 'apiClient/api'
import { FormsDevTierStats, FormsEnableDevTier } from 'apiClient/api/interface'

const FreeTier = () => {
  const { provider } = useParams<{ provider: string }>() || ''
  const [loading, setLoading] = useState(false)
  const [enable, setEnable] = useState<FormsEnableDevTier>({
    enable_on_aws: false,
    enable_on_gcp: false
  })
  const [count, setCount] = useState(0)

  const enableSettingKey =
    `enable_on_${provider.toLowerCase()}` as keyof FormsEnableDevTier
  const countKey =
    `${provider.toLowerCase()}_active_clusters_count` as keyof FormsDevTierStats

  useEffect(() => {
    fetchSettings(true)
    fetchCount()
    // eslint-disable-next-line
  }, [])

  async function fetchSettings(showLoading = false) {
    setLoading(showLoading)

    try {
      const data = (await getSystemSettings()).data
      setEnable(data?.enable_dev_tier)
      setLoading(false)
    } catch (e) {
      console.error(e)
    }
  }

  async function fetchCount() {
    try {
      const data = (await getDashboardStats()).data
      setCount(data?.dev_tier?.[countKey] as number)
    } catch (e) {
      console.error(e)
    }
  }

  const handleConfirm = async () => {
    setLoading(true)

    try {
      const enable_dev_tier = {
        ...enable,
        [enableSettingKey]: !enable?.[enableSettingKey]
      }
      await updateSystemSettings(
        {
          enable_dev_tier
        },
        {
          isShowMessage: true
        }
      )
      setEnable(enable_dev_tier)
      setLoading(false)
    } catch (e) {
      console.error(e)
    }
  }

  const handleReload = () => {
    fetchSettings()
    fetchCount()
  }

  return (
    <div style={{ marginBottom: '2em' }}>
      <div className="action" style={{ textAlign: 'right' }}>
        <Button icon={<ReloadOutlined />} onClick={handleReload}>
          Reload
        </Button>
      </div>
      <Descriptions>
        <Descriptions.Item label="Current Status">
          <Popconfirm
            title={`Are you sure to ${
              enable?.[enableSettingKey] ? 'turn off' : 'turn on'
            } the dev tier?`}
            onConfirm={handleConfirm}
            okText="Yes"
            cancelText="No"
            // Temporarily disable operations on GCP
            disabled={provider === 'gcp'}
          >
            <Switch
              checkedChildren="Enabled"
              unCheckedChildren="Disabled"
              loading={loading}
              defaultChecked={enable?.[enableSettingKey]}
              checked={enable?.[enableSettingKey]}
              // Temporarily disable operations on GCP
              disabled={provider === 'gcp'}
            />
          </Popconfirm>
        </Descriptions.Item>
        <Descriptions.Item label="Total Dev Tier Clusters to Date">
          <Statistic value={count} valueStyle={{ fontSize: '1em' }} />
        </Descriptions.Item>
      </Descriptions>
    </div>
  )
}

export default FreeTier
