import React, { useEffect, useMemo } from 'react'

import {
  CheckCircleFilled,
  CloudUploadOutlined,
  ReloadOutlined
} from '@ant-design/icons'
import { getValueFormat } from '@baurine/grafana-value-formats'
import { Popover, Text } from '@mantine/core'
import { IconChevronDown } from '@tabler/icons-react'
import { Progress } from 'antd'
import clsx from 'clsx'
import useSWR from 'swr'

import { listTasks } from '~/api'
import LoadingSpin from '~/components/LoadingSpin'
import { useCurOrg } from '~/hooks/state'

const TaskIcon: React.FC<{ taskType: string; progress: number }> = ({
  taskType,
  progress
}) => {
  const color = useMemo(() => {
    if (progress === -2) {
      return 'var(--cc-error-color)'
    }
    if (progress < 100) {
      return '#808080' // TODO
    }
    return 'var(--cc-primary-color)'
  }, [progress])

  // taskType real value: Upload, Rebuild
  if (taskType.toLowerCase() === 'upload') {
    return <CloudUploadOutlined style={{ fontSize: 24, color }} />
  }
  return <ReloadOutlined style={{ fontSize: 24, color }} />
}

const ProcessStatus: React.FC<{ progress: number }> = ({ progress }) => {
  if (progress === -2) {
    // fail
    return (
      <Progress
        type='circle'
        percent={50}
        status='exception'
        width={24}
        strokeWidth={10}
        format={() => '!'}
      />
    )
  }
  if (progress < 100) {
    return (
      <Progress
        type='circle'
        percent={progress}
        width={24}
        strokeWidth={10}
        showInfo={false}
      />
    )
  }

  // progress === 100
  return (
    <CheckCircleFilled
      style={{ fontSize: 24, color: 'var(--cc-primary-color)' }}
    />
  )
}

const PopoverContent: React.FC = () => {
  const { curOrg } = useCurOrg()
  const {
    data: tasksRes,
    error,
    mutate: reloadTasks
  } = useSWR(curOrg ? `/orgs/${curOrg.id}/tasks` : null, () =>
    listTasks(curOrg?.id!)
  )
  const loading = !tasksRes && !error

  useEffect(() => {
    const timerId = setInterval(() => {
      reloadTasks()
    }, 5000)

    return () => clearInterval(timerId)
  }, [reloadTasks])

  if (loading) {
    return (
      <div className='text-center'>
        <LoadingSpin />
      </div>
    )
  }

  if (tasksRes?.data.length === 0) {
    return <div className='text-center text-gray-500'>No running tasks</div>
  }

  return (
    <div className='flex flex-col gap-y-2'>
      <Text color='dimmed'>Latest 5 tasks</Text>

      {(tasksRes?.data || []).map((t, idx) => (
        <div className='flex items-center h-8' key={idx}>
          <TaskIcon taskType={t.taskType!} progress={t.process!} />
          <div
            className={clsx(
              'flex-1 pl-2 max-w-[320px] min-w-[150px] text-sm',
              t.process! < 100 && t.process! >= 0 && 'text-gray-500'
            )}
          >
            <div className='overflow-hidden whitespace-nowrap text-ellipsis pr-2'>
              {t.name}
            </div>
            {t.taskType === 'upload' && (
              <div>{getValueFormat('decbytes')(t.size || 0)}</div>
            )}
          </div>
          <ProcessStatus progress={t.process!} />
        </div>
      ))}
    </div>
  )
}

const NewTaskList: React.FC = () => {
  return (
    <Popover shadow='md' width={320} position='bottom-end'>
      <Popover.Target>
        <div className='flex items-center gap-1 cursor-pointer'>
          <Text fz='sm' weight={500}>
            Task List
          </Text>
          <IconChevronDown size={16} />
        </div>
      </Popover.Target>

      <Popover.Dropdown>
        <PopoverContent />
      </Popover.Dropdown>
    </Popover>
  )
}

export default NewTaskList
