import React from 'react'
import { Layout, Card, List, Badge, Button, Empty } from 'antd'
import { 
  MobileOutlined, 
  AndroidOutlined, 
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  CloseCircleOutlined 
} from '@ant-design/icons'
import { useSelector, useDispatch } from 'react-redux'
import type { RootState, AppDispatch } from '../../store/store'
import { selectDevice, selectFilteredDevices } from '../../store/slices/deviceSlice'
import { setDeviceInputBlocked } from '../../store/slices/uiSlice'

const { Sider } = Layout

interface SidebarProps {
  collapsed: boolean
}

/**
 * 侧边栏组件
 */
const Sidebar: React.FC<SidebarProps> = ({ collapsed }) => {
  const dispatch = useDispatch<AppDispatch>()
  const { connectedDevices, selectedDeviceId } = useSelector((state: RootState) => state.devices)
  const filteredDevices = useSelector((state: RootState) => selectFilteredDevices(state))
  const { status: connectionStatus } = useSelector((state: RootState) => state.connection)

  const getDeviceStatusIcon = (status: string) => {
    switch (status) {
      case 'online':
        return <CheckCircleOutlined style={{ color: 'var(--md-success)' }} />
      case 'busy':
        return <ExclamationCircleOutlined style={{ color: 'var(--md-warning)' }} />
      default:
        return <CloseCircleOutlined style={{ color: 'var(--md-error)' }} />
    }
  }

  const formatLastSeen = (timestamp: number) => {
    const diff = Date.now() - timestamp
    if (diff < 60000) return '刚刚'
    if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
    return `${Math.floor(diff / 86400000)}天前`
  }

  const handleDeviceSelect = (deviceId: string) => {
    dispatch(selectDevice(deviceId))
    
    // 找到选中的设备并同步输入阻止状态
    const selectedDevice = connectedDevices.find(d => d.id === deviceId)
    if (selectedDevice && selectedDevice.inputBlocked !== undefined) {
      dispatch(setDeviceInputBlocked(selectedDevice.inputBlocked))
    }
  }

  if (collapsed) {
    return (
      <Sider 
        width={80}
        collapsed={true}
        style={{ 
          background: 'var(--md-surface-container-lowest)',
          borderRight: '1px solid var(--md-outline-variant)'
        }}
      >
        <div style={{ padding: '16px 8px' }}>
          <Badge count={filteredDevices.length} size="small">
            <MobileOutlined style={{ fontSize: '24px' }} />
          </Badge>
        </div>
      </Sider>
    )
  }

  return (
    <Sider 
      width={300}
      style={{ 
        background: 'var(--md-surface-container-lowest)',
        borderRight: '1px solid var(--md-outline-variant)'
      }}
    >
      <div style={{ padding: '16px' }}>
        <Card 
          title={
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
              <MobileOutlined />
              连接的设备
              <Badge count={filteredDevices.length} size="small" />
            </div>
          }
          size="small"
          style={{ height: '100%' }}
          styles={{ body: { padding: 0, maxHeight: 'calc(100vh - 200px)', overflow: 'auto' } }}
        >
          {filteredDevices.length === 0 ? (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="未找到匹配的设备"
              style={{ padding: '40px 20px' }}
            >
              {connectionStatus !== 'connected' && (
                <Button type="primary" size="small">
                  连接服务器
                </Button>
              )}
            </Empty>
          ) : (
            <List
              dataSource={filteredDevices}
              renderItem={(device) => (
                <List.Item
                  style={{
                    padding: '12px 16px',
                    cursor: 'pointer',
                    backgroundColor: selectedDeviceId === device.id ? 'var(--md-primary-container)' : 'transparent',
                    borderLeft: selectedDeviceId === device.id ? '3px solid var(--md-primary)' : '3px solid transparent'
                  }}
                  onClick={() => handleDeviceSelect(device.id)}
                >
                  <List.Item.Meta
                    avatar={
                      <div style={{ position: 'relative' }}>
                        <AndroidOutlined style={{ fontSize: '32px', color: 'var(--md-secondary)' }} />
                        <div style={{ 
                          position: 'absolute', 
                          bottom: -2, 
                          right: -2,
                          background: 'var(--md-surface-container-lowest)',
                          borderRadius: '50%',
                          border: '1px solid var(--md-outline-variant)'
                        }}>
                          {getDeviceStatusIcon(device.status)}
                        </div>
                      </div>
                    }
                    title={
                      <div style={{ 
                        fontWeight: selectedDeviceId === device.id ? 'bold' : 'normal',
                        color: selectedDeviceId === device.id ? 'var(--md-primary)' : 'inherit'
                      }}>
                        {device.name}
                      </div>
                    }
                    description={
                      <div style={{ fontSize: '12px', color: 'var(--md-on-surface-variant)' }}>
                        <div>{device.model}</div>
                        <div>Android {device.osVersion}</div>
                        <div>{device.screenWidth}×{device.screenHeight}</div>
                        <div>IP: {device.publicIP || '未知'}</div>
                        <div>{formatLastSeen(device.lastSeen)}</div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          )}
        </Card>
      </div>
    </Sider>
  )
}

export default Sidebar 