import React, { useContext } from 'react'
import {
  Descriptions,
  Button,
  Typography,
  Flex,
  Space,
  Dropdown,
  message
} from 'antd'
import ReloadIcon from '../../Icons/ReloadIcon.jsx'
import { PrintServerContext } from '../context/PrintServerContext.js'
import BoolDisplay from '../common/BoolDisplay.jsx'

const { Text, Paragraph } = Typography

const PrintServerContextDebug = () => {
  const { printServer, error, connecting } = useContext(PrintServerContext)
  const [msgApi, contextHolder] = message.useMessage()

  const actionItems = {
    items: [
      {
        label: 'Reload',
        key: 'reload',
        icon: <ReloadIcon />
      }
    ],
    onClick: ({ key }) => {
      if (key === 'reload') {
        msgApi.info('Reloading Page...')
        window.location.reload()
      }
    }
  }

  // Helper to display socket info safely
  const getSocketInfo = () => {
    if (!printServer) return 'n/a'
    // Only show safe properties
    const { id, connected, disconnected, nsp } = printServer
    return JSON.stringify({ id, connected, disconnected, nsp }, null, 2)
  }

  return (
    <Flex vertical gap='large' style={{ height: '100%', minHeight: 0 }}>
      {contextHolder}
      <Flex justify={'space-between'} align={'center'}>
        <Space>
          <Dropdown menu={actionItems}>
            <Button>Actions</Button>
          </Dropdown>
        </Space>
      </Flex>
      <div style={{ height: '100%', overflow: 'auto' }}>
        <Descriptions bordered column={1}>
          <Descriptions.Item label='Connected'>
            <BoolDisplay value={printServer?.connected || false} />
          </Descriptions.Item>
          <Descriptions.Item label='Connecting'>
            <BoolDisplay value={connecting} />
          </Descriptions.Item>
          <Descriptions.Item label='Error'>
            {error ? <Text type='danger'>{error}</Text> : <Text>n/a</Text>}
          </Descriptions.Item>
          <Descriptions.Item label='Socket'>
            <Paragraph>
              <pre>{getSocketInfo()}</pre>
            </Paragraph>
          </Descriptions.Item>
        </Descriptions>
      </div>
    </Flex>
  )
}

export default PrintServerContextDebug
