import React, { useEffect } from 'react'
import { Form, Select, DatePicker, Button, Space } from 'antd'
import { SearchOutlined, ClearOutlined, FilterOutlined } from '@ant-design/icons'
import { useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from '../../store/store'
import type { DeviceFilter } from '../../store/slices/deviceSlice'
import { updateDeviceFilter, clearDeviceFilter } from '../../store/slices/deviceSlice'
import dayjs from 'dayjs'

const { Option } = Select
const { RangePicker } = DatePicker

interface DeviceFilterProps {
  onFilterChange?: (filter: DeviceFilter) => void
  style?: React.CSSProperties
}

/**
 * 设备筛选组件
 */
const DeviceFilterComponent: React.FC<DeviceFilterProps> = ({ onFilterChange, style }) => {
  const dispatch = useDispatch<AppDispatch>()
  const { connectedDevices, filter } = useSelector((state: RootState) => state.devices)
  const [form] = Form.useForm()

  // 获取所有可选的选项
  const getUniqueValues = (key: keyof DeviceFilter) => {
    const values = connectedDevices
      .map(device => device[key as keyof typeof device])
      .filter((value): value is string => typeof value === 'string' && value !== '')
    return Array.from(new Set(values)).sort()
  }

  // 获取所有型号
  const modelOptions = getUniqueValues('model')
  
  // 获取所有系统版本
  const osVersionOptions = getUniqueValues('osVersion')
  
  // 获取所有APP名称
  const appNameOptions = getUniqueValues('appName')

  // 初始化表单值
  useEffect(() => {
    form.setFieldsValue({
      model: filter.model,
      osVersion: filter.osVersion,
      appName: filter.appName,
      isLocked: filter.isLocked,
      status: filter.status || '', // 如果没有status筛选，默认为空字符串（全部）
      connectedAtRange: filter.connectedAtRange ? [
        filter.connectedAtRange.start ? dayjs(filter.connectedAtRange.start) : null,
        filter.connectedAtRange.end ? dayjs(filter.connectedAtRange.end) : null
      ] : null
    })
  }, [filter, form])

  // 处理筛选
  const handleFilter = (values: any) => {
    const newFilter: DeviceFilter = {
      model: values.model,
      osVersion: values.osVersion,
      appName: values.appName,
      isLocked: values.isLocked,
      // status为空字符串表示"全部"，不设置status字段
      status: values.status && values.status !== '' ? values.status as 'online' | 'offline' : undefined,
      connectedAtRange: values.connectedAtRange ? {
        start: values.connectedAtRange[0]?.valueOf(),
        end: values.connectedAtRange[1]?.valueOf()
      } : undefined
    }

    // 移除空值
    Object.keys(newFilter).forEach(key => {
      if (newFilter[key as keyof DeviceFilter] === undefined || 
          newFilter[key as keyof DeviceFilter] === '') {
        delete newFilter[key as keyof DeviceFilter]
      }
    })

    dispatch(updateDeviceFilter(newFilter))
    onFilterChange?.(newFilter)
  }

  // 清除筛选
  const handleClear = () => {
    form.resetFields()
    dispatch(clearDeviceFilter())
    onFilterChange?.({})
  }

  // 获取筛选结果数量
  const getFilteredCount = () => {
    const hasFilter = Object.keys(filter).length > 0
    return hasFilter ? '已筛选' : '全部'
  }

  return (
    <div className="device-filter-bar" style={style}>
      <Form
        form={form}
        layout="inline"
        onFinish={handleFilter}
        size="small"
        style={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: '8px',
          flexWrap: 'wrap'
        }}
      >
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: '8px',
          marginRight: '16px',
          fontWeight: 500,
          color: '#262626'
        }}>
          <FilterOutlined style={{ color: 'var(--md-primary)' }} />
          筛选
          <span style={{ fontSize: '12px', color: '#666' }}>
            ({getFilteredCount()})
          </span>
        </div>

        <Form.Item name="model" style={{ marginBottom: 0 }}>
          <Select
            placeholder="型号"
            allowClear
            showSearch
            style={{ width: 120 }}
            filterOption={(input, option) => {
              const label = String((option as any)?.children ?? (option as any)?.label ?? '')
              return label.toLowerCase().includes(input.toLowerCase())
            }}
          >
            {modelOptions.map(model => (
              <Option key={model} value={model}>{model}</Option>
            ))}
          </Select>
        </Form.Item>
        
        <Form.Item name="osVersion" style={{ marginBottom: 0 }}>
          <Select
            placeholder="系统版本"
            allowClear
            showSearch
            style={{ width: 120 }}
            filterOption={(input, option) => {
              const label = String((option as any)?.children ?? (option as any)?.label ?? '')
              return label.toLowerCase().includes(input.toLowerCase())
            }}
          >
            {osVersionOptions.map(version => (
              <Option key={version} value={version}>Android {version}</Option>
            ))}
          </Select>
        </Form.Item>
        
        <Form.Item name="appName" style={{ marginBottom: 0 }}>
          <Select
            placeholder="APP名称"
            allowClear
            showSearch
            style={{ width: 120 }}
            filterOption={(input, option) => {
              const label = String((option as any)?.children ?? (option as any)?.label ?? '')
              return label.toLowerCase().includes(input.toLowerCase())
            }}
          >
            {appNameOptions.map(appName => (
              <Option key={appName} value={appName}>{appName}</Option>
            ))}
          </Select>
        </Form.Item>
        
        <Form.Item name="isLocked" style={{ marginBottom: 0 }}>
          <Select 
            placeholder="锁屏状态" 
            allowClear
            style={{ width: 100 }}
          >
            <Option value={false}>未锁定</Option>
            <Option value={true}>已锁定</Option>
          </Select>
        </Form.Item>
        
        <Form.Item name="status" style={{ marginBottom: 0 }}>
          <Select 
            placeholder="在线状态" 
            allowClear={false}
            style={{ width: 120 }}
          >
            <Option value="">全部</Option>
            <Option value="online">在线</Option>
            <Option value="offline">离线</Option>
          </Select>
        </Form.Item>
        
        <Form.Item name="connectedAtRange" style={{ marginBottom: 0 }}>
          <RangePicker
            placeholder={['开始', '结束']}
            style={{ width: 240 }}
            showTime
            format="MM-DD HH:mm"
            size="small"
          />
        </Form.Item>

        <Space style={{ marginLeft: 'auto' }}>
          <Button 
            type="primary" 
            icon={<SearchOutlined />} 
            onClick={() => form.submit()}
            size="small"
          >
            筛选
          </Button>
          <Button 
            icon={<ClearOutlined />} 
            onClick={handleClear}
            size="small"
          >
            清除
          </Button>
        </Space>
      </Form>
    </div>
  )
}

export default DeviceFilterComponent
