import PropTypes from 'prop-types'
import { Typography, Tag } from 'antd' // eslint-disable-line
import { useState, useContext, useEffect } from 'react'
import { PrintServerContext } from '../context/PrintServerContext'
import QuestionCircleIcon from '../../Icons/QuestionCircleIcon'
import PauseCircleIcon from '../../Icons/PauseCircleIcon'
import XMarkCircleIcon from '../../Icons/XMarkCircleIcon'
import CheckCircleIcon from '../../Icons/CheckCircleIcon'

const SubJobCounter = ({
  job,
  showIcon = true,
  state = { type: 'complete' }
}) => {
  const { printServer } = useContext(PrintServerContext)
  const [initialized, setInitialized] = useState(false)
  var badgeStatus = 'unknown'
  var badgeIcon = <QuestionCircleIcon />
  const [subJobs, setSubJobs] = useState(job.subJobs)

  const [count, setCount] = useState(0)

  useEffect(() => {
    if (printServer && !initialized && job?.id) {
      setInitialized(true)
      printServer.on('notify_subjob_update', (statusUpdate) => {
        for (const subJob of job.subJobs) {
          if (statusUpdate?._id === subJob.id && statusUpdate?.state) {
            setSubJobs((prev) => [...prev, statusUpdate])
          }
        }
      })
    }
    return () => {
      if (printServer && initialized) {
        printServer.off('notify_subjob_update')
      }
    }
  }, [printServer, initialized, job?.subJobs, job?.id])

  switch (state.type) {
    case 'draft':
      badgeStatus = 'default'
      badgeIcon = <QuestionCircleIcon />
      break
    case 'printing':
      badgeStatus = 'processing'
      badgeIcon = <CheckCircleIcon />
      break
    case 'complete':
      badgeStatus = 'success'
      badgeIcon = <CheckCircleIcon />
      break
    case 'failed':
      badgeStatus = 'error'
      badgeIcon = <XMarkCircleIcon />
      break
    case 'queued':
      badgeStatus = 'warning'
      badgeIcon = <PauseCircleIcon />
      break
    case 'paused':
      badgeStatus = 'warning'
      badgeIcon = <PauseCircleIcon />
      break
    case 'cancelled':
      badgeIcon = <XMarkCircleIcon />
      break
    default:
      badgeStatus = 'default'
  }

  useEffect(() => {
    setCount(0)
    for (let subJob of subJobs) {
      if (subJob.state.type === state.type) {
        setCount((prevCount) => prevCount + 1)
      }
    }
  }, [subJobs, state.type])

  return (
    <Tag
      count={badgeIcon}
      color={badgeStatus}
      icon={showIcon ? badgeIcon : null}
    >
      {count.toString()}
    </Tag>
  )
}

SubJobCounter.propTypes = {
  state: PropTypes.shape({
    type: PropTypes.string
  }),
  job: PropTypes.shape({
    id: PropTypes.string,
    subJobs: PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.string,
        subJobId: PropTypes.string,
        state: PropTypes.shape({
          type: PropTypes.string,
          progress: PropTypes.number
        })
      })
    )
  }),
  showIcon: PropTypes.bool
}

export default SubJobCounter
