// PrinterSelect.js
import PropTypes from 'prop-types'
import {
  Badge,
  Progress,
  Flex,
  Space,
  Tag,
  Typography,
  Button,
  Tooltip
} from 'antd'
import React, { useState, useContext, useEffect } from 'react'
import { SocketContext } from '../context/SocketContext'
import { CaretRightOutlined } from '@ant-design/icons'
import XMarkIcon from '../../Icons/XMarkIcon'
import PauseIcon from '../../Icons/PauseIcon'

const PrinterState = ({
  printer,
  showProgress = true,
  showStatus = true,
  showPrinterName = true,
  showControls = true
}) => {
  const { socket } = useContext(SocketContext)
  const [badgeStatus, setBadgeStatus] = useState('unknown')
  const [badgeText, setBadgeText] = useState('Unknown')
  const [currentState, setCurrentState] = useState(
    printer?.state || {
      type: 'unknown',
      progress: 0
    }
  )
  const [initialized, setInitialized] = useState(false)
  const { Text } = Typography

  useEffect(() => {
    if (socket && !initialized && printer?.id) {
      setInitialized(true)
      socket.on('notify_printer_update', (statusUpdate) => {
        if (statusUpdate?._id === printer.id && statusUpdate?.state) {
          setCurrentState(statusUpdate.state)
        }
      })
    }
    return () => {
      if (socket && initialized) {
        socket.off('notify_printer_update')
      }
    }
  }, [socket, initialized, printer?.id])

  useEffect(() => {
    switch (currentState.type) {
      case 'online':
        setBadgeStatus('success')
        setBadgeText('Online')
        break
      case 'standby':
        setBadgeStatus('success')
        setBadgeText('Standby')
        break
      case 'complete':
        setBadgeStatus('success')
        setBadgeText('Complete')
        break
      case 'offline':
        setBadgeStatus('default')
        setBadgeText('Offline')
        break
      case 'shutdown':
        setBadgeStatus('default')
        setBadgeText('Shutdown')
        break
      case 'initializing':
        setBadgeStatus('warning')
        setBadgeText('Initializing')
        break
      case 'printing':
        setBadgeStatus('processing')
        setBadgeText('Printing')
        break
      case 'paused':
        setBadgeStatus('warning')
        setBadgeText('Paused')
        break
      case 'cancelled':
        setBadgeStatus('warning')
        setBadgeText('Cancelled')
        break
      case 'loading':
        setBadgeStatus('processing')
        setBadgeText('Uploading')
        break
      case 'processing':
        setBadgeStatus('processing')
        setBadgeText('Processing')
        break
      case 'ready':
        setBadgeStatus('success')
        setBadgeText('Ready')
        break
      case 'error':
        setBadgeStatus('error')
        setBadgeText('Error')
        break
      case 'startup':
        setBadgeStatus('warning')
        setBadgeText('Startup')
        break
      default:
        setBadgeStatus('default')
        setBadgeText(currentState.type)
    }
  }, [currentState])

  return (
    <Flex gap='small' align={'center'}>
      {showPrinterName && <Text>{printer.name}</Text>}
      {showStatus && (
        <Space>
          <Tag color={badgeStatus} style={{ marginRight: 0 }}>
            <Flex gap={6}>
              <Badge status={badgeStatus} />
              {badgeText}
            </Flex>
          </Tag>
        </Space>
      )}
      {showProgress &&
      (currentState.type === 'printing' ||
        currentState.type === 'deploying') ? (
        <Progress
          percent={Math.round(currentState.progress * 100)}
          status='active'
          style={{ width: '150px', marginBottom: '2px' }}
        />
      ) : null}
      {showControls && currentState.type === 'printing' ? (
        <Space.Compact>
          <Tooltip
            title={currentState.type === 'printing' ? 'Pause' : 'Resume'}
            arrow={false}
          >
            <Button
              onClick={() => {
                if (currentState.type === 'printing') {
                  socket.emit('printer.print.pause', {
                    printerId: printer.id
                  })
                } else {
                  socket.emit('printer.print.resume', {
                    printerId: printer.id
                  })
                }
              }}
              style={{ height: '22px' }}
              type='text'
              icon={
                currentState.type === 'printing' ? (
                  <PauseIcon
                    style={{ fontSize: '12px', marginBottom: '3px' }}
                  />
                ) : (
                  <CaretRightOutlined
                    style={{ fontSize: '10px', marginBottom: '3px' }}
                  />
                )
              }
            ></Button>
          </Tooltip>
          <Tooltip title='Cancel' arrow={false}>
            <Button
              onClick={() => {
                socket.emit('printer.print.cancel', {
                  printerId: printer.id
                })
              }}
              type='text'
              style={{ height: '22px' }}
              icon={
                <XMarkIcon style={{ fontSize: '12px', marginBottom: '3px' }} />
              }
            />
          </Tooltip>
        </Space.Compact>
      ) : null}
    </Flex>
  )
}

PrinterState.propTypes = {
  printer: PropTypes.shape({
    id: PropTypes.string,
    name: PropTypes.string,
    state: PropTypes.shape({
      type: PropTypes.string,
      progress: PropTypes.number
    })
  }),
  showProgress: PropTypes.bool,
  showStatus: PropTypes.bool,
  showPrinterName: PropTypes.bool,
  showControls: PropTypes.bool
}

export default PrinterState
