'use client'
import { useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Plus, BarChart3, Search, RotateCcw, X, Eye, Settings, ChevronLeft, ChevronRight, AlertTriangle } from 'lucide-react'
import { useApi } from '@/lib/hooks'

interface RepairOrder {
  id: string
  sn: string
  fault_type: string
  status: string
  priority: string
  assignee: string
  create_date: string
  description: string
}

const statusOptions = ['全部', '待处理', '处理中', '已处理']
const priorityOptions = ['全部', '高', '中', '低']
const assigneeOptions = ['全部', '张工', '李工', '王工', '赵工']
const faultTypeOptions = ['板卡故障', '固件异常', '通信故障', '电源故障', '传感器故障', '其他']

function getStatusStyle(status: string) {
  switch (status) {
    case '处理中': return { backgroundColor: '#eef5f0', color: '#4a7c59', border: '1px solid #a3c4ad' }
    case '已处理': return { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' }
    case '待处理': return { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.65)', border: '1px solid #D9D9D9' }
    default: return { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.65)', border: '1px solid #D9D9D9' }
  }
}

function getStatusEmoji(status: string) {
  switch (status) {
    case '处理中': return '🔧'
    case '已处理': return '✅'
    case '待处理': return '⏳'
    default: return ''
  }
}

function getPriorityStyle(priority: string) {
  switch (priority) {
    case '高': return { backgroundColor: '#FFF1F0', color: '#FF4D4F', border: '1px solid #FFCCC7' }
    case '中': return { backgroundColor: '#FFF7E6', color: '#FA8C16', border: '1px solid #FFD591' }
    case '低': return { backgroundColor: '#F0F5FF', color: '#597EF7', border: '1px solid #ADC6FF' }
    default: return { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.65)', border: '1px solid #D9D9D9' }
  }
}

export default function RepairPage() {
  const router = useRouter()
  const { data: ordersRaw, loading, refetch } = useApi<RepairOrder[]>('/api/repair', [])
  const { data: devicesData } = useApi<{ sn: string; model: string; type: string; firmware: string }[]>('/api/devices', [])

  // Map DB fields to display fields
  const ordersData = ordersRaw.map(o => ({
    id: o.id, sn: o.sn, faultType: o.fault_type, status: o.status,
    priority: o.priority, assignee: o.assignee, createDate: o.create_date, description: o.description,
  }))

  // Build device info map from devices API
  const deviceInfoMap: Record<string, { model: string; type: string; firmware: string }> = {}
  devicesData.forEach(d => { deviceInfoMap[d.sn] = { model: d.model, type: d.type, firmware: d.firmware } })
  const snOptions = devicesData.map(d => d.sn)

  const [filterStatus, setFilterStatus] = useState('全部')
  const [filterPriority, setFilterPriority] = useState('全部')
  const [filterAssignee, setFilterAssignee] = useState('全部')
  const [filterDateFrom, setFilterDateFrom] = useState('')
  const [filterDateTo, setFilterDateTo] = useState('')
  const [filterSN, setFilterSN] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [newDrawer, setNewDrawer] = useState(false)
  const [processDrawer, setProcessDrawer] = useState<typeof ordersData[0] | null>(null)
  const [detailDrawer, setDetailDrawer] = useState<typeof ordersData[0] | null>(null)

  // New order form
  const [newSN, setNewSN] = useState('')
  const [newFaultType, setNewFaultType] = useState('板卡故障')
  const [newDescription, setNewDescription] = useState('')
  const [newPhenomenon, setNewPhenomenon] = useState('')
  const [newPriority, setNewPriority] = useState('中')
  const [newAssignee, setNewAssignee] = useState('张工')
  const [newDate, setNewDate] = useState('')
  const [newNote, setNewNote] = useState('')

  // Process form
  const [processAction, setProcessAction] = useState('更换板卡')
  const [processOldBoard, setProcessOldBoard] = useState('')
  const [processNewBoard, setProcessNewBoard] = useState('')
  const [processBoardType, setProcessBoardType] = useState('主协板')
  const [processBoardModel, setProcessBoardModel] = useState('')
  const [processAuthChecks, setProcessAuthChecks] = useState<string[]>([])
  const [processNote, setProcessNote] = useState('')
  const [processScrap, setProcessScrap] = useState(false)

  if (loading) return <div style={{ padding: 24 }}>加载中...</div>

  const pageSize = 5
  const filteredOrders = ordersData.filter(o => {
    if (filterStatus !== '全部' && o.status !== filterStatus) return false
    if (filterPriority !== '全部' && o.priority !== filterPriority) return false
    if (filterAssignee !== '全部' && o.assignee !== filterAssignee) return false
    if (filterSN && !o.sn.toLowerCase().includes(filterSN.toLowerCase())) return false
    if (filterDateFrom && o.createDate < filterDateFrom) return false
    if (filterDateTo && o.createDate > filterDateTo) return false
    return true
  })
  const totalPages = Math.ceil(filteredOrders.length / pageSize)
  const pagedOrders = filteredOrders.slice((currentPage - 1) * pageSize, currentPage * pageSize)

  const resetFilters = () => {
    setFilterStatus('全部'); setFilterPriority('全部'); setFilterAssignee('全部')
    setFilterDateFrom(''); setFilterDateTo(''); setFilterSN(''); setCurrentPage(1)
  }

  const selectedDeviceInfo = newSN ? deviceInfoMap[newSN] : null

  return (
    <div style={{ padding: 24 }}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <div>
          <h2 style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>维修工单</h2>
          <p style={{ fontSize: 14, color: 'rgba(0,0,0,0.45)', margin: '4px 0 0' }}>管理设备维修工单</p>
        </div>
        <div style={{ display: 'flex', gap: 12 }}>
          <button onClick={() => router.push('/repair/stats')} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>
            <BarChart3 size={16} />维修统计
          </button>
          <button onClick={() => setNewDrawer(true)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>
            <Plus size={16} />新建工单
          </button>
        </div>
      </div>

      {/* Filter Card */}
      <div style={{ backgroundColor: '#fff', borderRadius: 8, padding: 20, marginBottom: 24, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 16 }}>
          <div>
            <label style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 4, display: 'block' }}>状态</label>
            <select value={filterStatus} onChange={e => { setFilterStatus(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 8px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
              {statusOptions.map(s => <option key={s} value={s}>{s}</option>)}
            </select>
          </div>
          <div>
            <label style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 4, display: 'block' }}>优先级</label>
            <select value={filterPriority} onChange={e => { setFilterPriority(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 8px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
              {priorityOptions.map(p => <option key={p} value={p}>{p}</option>)}
            </select>
          </div>
          <div>
            <label style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 4, display: 'block' }}>负责人</label>
            <select value={filterAssignee} onChange={e => { setFilterAssignee(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 8px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
              {assigneeOptions.map(a => <option key={a} value={a}>{a}</option>)}
            </select>
          </div>
          <div>
            <label style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 4, display: 'block' }}>开始日期</label>
            <input type="date" value={filterDateFrom} onChange={e => { setFilterDateFrom(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 8px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }} />
          </div>
          <div>
            <label style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 4, display: 'block' }}>结束日期</label>
            <input type="date" value={filterDateTo} onChange={e => { setFilterDateTo(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 8px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }} />
          </div>
          <div>
            <label style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 4, display: 'block' }}>设备SN</label>
            <input type="text" value={filterSN} onChange={e => { setFilterSN(e.target.value); setCurrentPage(1) }} placeholder="输入设备SN搜索" style={{ width: '100%', padding: '6px 8px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }} />
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button onClick={resetFilters} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 16px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>
            <RotateCcw size={14} />重置
          </button>
          <button onClick={() => setCurrentPage(1)} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 16px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>
            <Search size={14} />搜索
          </button>
        </div>
      </div>

      {/* Order List (Card Style) */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 24 }}>
        {pagedOrders.map(order => (
          <div key={order.id} style={{ backgroundColor: '#fff', borderRadius: 8, padding: 20, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
                  <span style={{ fontSize: 16, fontWeight: 600 }}>{order.id}</span>
                  <span style={{ ...getStatusStyle(order.status), padding: '2px 8px', borderRadius: 4, fontSize: 12 }}>
                    {getStatusEmoji(order.status)} {order.status}
                  </span>
                  <span style={{ ...getPriorityStyle(order.priority), padding: '2px 8px', borderRadius: 4, fontSize: 12 }}>
                    {order.priority}优先级
                  </span>
                </div>
                <div style={{ display: 'flex', gap: 24, fontSize: 14, color: 'rgba(0,0,0,0.65)' }}>
                  <span>SN: {order.sn}</span>
                  <span>故障类型: {order.faultType}</span>
                  <span>负责人: {order.assignee}</span>
                  <span>创建日期: {order.createDate}</span>
                </div>
                <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)', marginTop: 8 }}>{order.description}</div>
              </div>
              <div style={{ display: 'flex', gap: 8, flexShrink: 0, marginLeft: 16 }}>
                <button onClick={() => setDetailDrawer(order)} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 13, color: '#4a7c59' }}>
                  <Eye size={14} />详情
                </button>
                {(order.status === '处理中' || order.status === '待处理') && (
                  <button onClick={() => setProcessDrawer(order)} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 12px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 13 }}>
                    <Settings size={14} />处理
                  </button>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8 }}>
          <button onClick={() => setCurrentPage(p => Math.max(1, p - 1))} disabled={currentPage === 1} style={{ padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: currentPage === 1 ? 'not-allowed' : 'pointer', opacity: currentPage === 1 ? 0.5 : 1 }}>
            <ChevronLeft size={16} />
          </button>
          {Array.from({ length: totalPages }, (_, i) => i + 1).map(p => (
            <button key={p} onClick={() => setCurrentPage(p)} style={{ padding: '6px 12px', border: currentPage === p ? '1px solid #4a7c59' : '1px solid #D9D9D9', borderRadius: 6, backgroundColor: currentPage === p ? '#4a7c59' : '#fff', color: currentPage === p ? '#fff' : 'rgba(0,0,0,0.65)', cursor: 'pointer', fontSize: 14, minWidth: 36 }}>
              {p}
            </button>
          ))}
          <button onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))} disabled={currentPage === totalPages} style={{ padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: currentPage === totalPages ? 'not-allowed' : 'pointer', opacity: currentPage === totalPages ? 0.5 : 1 }}>
            <ChevronRight size={16} />
          </button>
          <span style={{ fontSize: 14, color: 'rgba(0,0,0,0.45)', marginLeft: 8 }}>共 {filteredOrders.length} 条</span>
        </div>
      )}

      {/* New Order Drawer */}
      {newDrawer && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setNewDrawer(false)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 520, backgroundColor: '#fff', boxShadow: '-2px 0 8px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px', borderBottom: '1px solid #F0F0F0' }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>新建维修工单</h3>
              <button onClick={() => setNewDrawer(false)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
              {/* 设备信息 */}
              <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0' }}>设备信息</h4>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>设备SN</label>
                <select value={newSN} onChange={e => setNewSN(e.target.value)} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                  <option value="">请选择设备</option>
                  {snOptions.map(sn => <option key={sn} value={sn}>{sn}</option>)}
                </select>
              </div>
              {selectedDeviceInfo && (
                <div style={{ padding: 12, backgroundColor: '#FAFAFA', borderRadius: 6, marginBottom: 16, fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>
                  <div>型号：{selectedDeviceInfo.model} ({selectedDeviceInfo.type})</div>
                  <div>固件：{selectedDeviceInfo.firmware}</div>
                </div>
              )}

              {/* 故障信息 */}
              <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0' }}>故障信息</h4>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>故障类型</label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {faultTypeOptions.map(ft => (
                    <button key={ft} onClick={() => setNewFaultType(ft)} style={{ padding: '6px 14px', borderRadius: 6, fontSize: 13, cursor: 'pointer', border: newFaultType === ft ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: newFaultType === ft ? '#eef5f0' : '#fff', color: newFaultType === ft ? '#4a7c59' : 'rgba(0,0,0,0.65)' }}>{ft}</button>
                  ))}
                </div>
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>故障描述</label>
                <textarea value={newDescription} onChange={e => setNewDescription(e.target.value)} rows={3} placeholder="请描述故障情况" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, resize: 'vertical', boxSizing: 'border-box' }} />
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>故障现象</label>
                <textarea value={newPhenomenon} onChange={e => setNewPhenomenon(e.target.value)} rows={2} placeholder="请描述故障现象" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, resize: 'vertical', boxSizing: 'border-box' }} />
              </div>

              {/* 工单信息 */}
              <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0' }}>工单信息</h4>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>优先级</label>
                <div style={{ display: 'flex', gap: 8 }}>
                  {['低', '中', '高'].map(p => (
                    <button key={p} onClick={() => setNewPriority(p)} style={{ padding: '6px 20px', borderRadius: 6, fontSize: 13, cursor: 'pointer', ...( newPriority === p ? getPriorityStyle(p) : { border: '1px solid #D9D9D9', backgroundColor: '#fff', color: 'rgba(0,0,0,0.65)' }) }}>{p}</button>
                  ))}
                </div>
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>维修人员</label>
                <select value={newAssignee} onChange={e => setNewAssignee(e.target.value)} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                  {assigneeOptions.filter(a => a !== '全部').map(a => <option key={a} value={a}>{a}</option>)}
                </select>
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>预计修复时间</label>
                <input type="date" value={newDate} onChange={e => setNewDate(e.target.value)} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>备注</label>
                <textarea value={newNote} onChange={e => setNewNote(e.target.value)} rows={2} placeholder="备注信息" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, resize: 'vertical', boxSizing: 'border-box' }} />
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setNewDrawer(false)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={async () => {
                if (!newSN) return
                const orderId = `WO-${new Date().getFullYear()}-${String(ordersData.length + 1).padStart(4, '0')}`
                await fetch('/api/repair', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: orderId, sn: newSN, fault_type: newFaultType, status: '待处理', priority: newPriority, assignee: newAssignee, create_date: new Date().toISOString().slice(0, 10), description: newDescription }) })
                refetch(); setNewDrawer(false); setNewSN(''); setNewDescription(''); setNewPhenomenon('')
              }} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>创建工单</button>
            </div>
          </div>
        </div>
      )}

      {/* Process Drawer */}
      {processDrawer && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setProcessDrawer(null)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 520, backgroundColor: '#fff', boxShadow: '-2px 0 8px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px', borderBottom: '1px solid #F0F0F0' }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>处理工单 - {processDrawer.id}</h3>
              <button onClick={() => setProcessDrawer(null)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
              <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0' }}>处理操作</h4>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 20 }}>
                {['更换板卡', '固件修复', '参数重置', '其他处理'].map(a => (
                  <button key={a} onClick={() => setProcessAction(a)} style={{ padding: '6px 14px', borderRadius: 6, fontSize: 13, cursor: 'pointer', border: processAction === a ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: processAction === a ? '#eef5f0' : '#fff', color: processAction === a ? '#4a7c59' : 'rgba(0,0,0,0.65)' }}>{a}</button>
                ))}
              </div>

              {processAction === '更换板卡' && (
                <>
                  <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0' }}>板卡更换</h4>
                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>板卡类型</label>
                    <select value={processBoardType} onChange={e => setProcessBoardType(e.target.value)} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                      {['主协板', '采集板', '发射板', '升压板'].map(t => <option key={t} value={t}>{t}</option>)}
                    </select>
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>板卡型号</label>
                    <input value={processBoardModel} onChange={e => setProcessBoardModel(e.target.value)} placeholder="请输入板卡型号" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>原板卡SN</label>
                    <input value={processOldBoard} onChange={e => setProcessOldBoard(e.target.value)} placeholder="请输入原板卡SN" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>新板卡SN</label>
                    <input value={processNewBoard} onChange={e => setProcessNewBoard(e.target.value)} placeholder="请输入新板卡SN" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                  </div>
                </>
              )}

              <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0' }}>授权处理</h4>
              <div style={{ marginBottom: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, cursor: 'pointer' }}>
                  <input type="checkbox" checked={processAuthChecks.includes('reauth')} onChange={() => setProcessAuthChecks(prev => prev.includes('reauth') ? prev.filter(x => x !== 'reauth') : [...prev, 'reauth'])} />
                  重新生成授权文件
                </label>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, cursor: 'pointer' }}>
                  <input type="checkbox" checked={processAuthChecks.includes('firmware')} onChange={() => setProcessAuthChecks(prev => prev.includes('firmware') ? prev.filter(x => x !== 'firmware') : [...prev, 'firmware'])} />
                  推送适配固件
                </label>
              </div>

              <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, paddingBottom: 8, borderBottom: '1px solid #F0F0F0' }}>处理备注</h4>
              <textarea value={processNote} onChange={e => setProcessNote(e.target.value)} rows={3} placeholder="请输入处理备注" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, resize: 'vertical', boxSizing: 'border-box', marginBottom: 20 }} />

              {/* 报废处理 */}
              <div style={{ padding: 16, borderRadius: 8, border: '1px solid #FFCCC7', backgroundColor: '#FFF1F0' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <AlertTriangle size={16} style={{ color: '#FF4D4F' }} />
                  <span style={{ fontSize: 14, fontWeight: 600, color: '#FF4D4F' }}>报废处理</span>
                </div>
                <p style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)', marginBottom: 12 }}>报废操作不可逆，请谨慎操作</p>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, cursor: 'pointer', marginBottom: 12 }}>
                  <input type="checkbox" checked={processScrap} onChange={e => setProcessScrap(e.target.checked)} />
                  申请报废此设备
                </label>
                {processScrap && (
                  <Link href="/scrap" style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '6px 14px', borderRadius: 6, fontSize: 13, border: '1px solid #FF4D4F', color: '#FF4D4F', backgroundColor: '#fff', textDecoration: 'none' }}>前往报废管理</Link>
                )}
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setProcessDrawer(null)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={() => setProcessDrawer(null)} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>提交处理</button>
            </div>
          </div>
        </div>
      )}

      {/* Detail Drawer */}
      {detailDrawer && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setDetailDrawer(null)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 540, backgroundColor: '#fff', boxShadow: '-2px 0 8px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px', borderBottom: '1px solid #F0F0F0' }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>工单详情 - {detailDrawer.id}</h3>
              <button onClick={() => setDetailDrawer(null)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
              {/* 工单信息 */}
              <div style={{ padding: 16, backgroundColor: '#FAFAFA', borderRadius: 8, marginBottom: 16, border: '1px solid #F0F0F0' }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>工单信息</h4>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, fontSize: 13 }}>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>工单号：</span>{detailDrawer.id}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>状态：</span><span style={{ ...getStatusStyle(detailDrawer.status), padding: '1px 6px', borderRadius: 4, fontSize: 12 }}>{detailDrawer.status}</span></div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>优先级：</span><span style={{ ...getPriorityStyle(detailDrawer.priority), padding: '1px 6px', borderRadius: 4, fontSize: 12 }}>{detailDrawer.priority}</span></div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>创建时间：</span>{detailDrawer.createDate}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>维修人员：</span>{detailDrawer.assignee}</div>
                </div>
              </div>

              {/* 设备信息 */}
              <div style={{ padding: 16, backgroundColor: '#FAFAFA', borderRadius: 8, marginBottom: 16, border: '1px solid #F0F0F0' }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>设备信息</h4>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, fontSize: 13 }}>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>设备SN：</span>{detailDrawer.sn}</div>
                  {deviceInfoMap[detailDrawer.sn] && (
                    <>
                      <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>型号：</span>{deviceInfoMap[detailDrawer.sn].model}</div>
                      <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>固件：</span>{deviceInfoMap[detailDrawer.sn].firmware}</div>
                      <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>位置：</span>{deviceInfoMap[detailDrawer.sn].location}</div>
                    </>
                  )}
                </div>
              </div>

              {/* 故障信息 */}
              <div style={{ padding: 16, backgroundColor: '#FAFAFA', borderRadius: 8, marginBottom: 16, border: '1px solid #F0F0F0' }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>故障信息</h4>
                <div style={{ fontSize: 13 }}>
                  <div style={{ marginBottom: 8 }}><span style={{ color: 'rgba(0,0,0,0.45)' }}>故障类型：</span>{detailDrawer.faultType}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>故障描述：</span>{detailDrawer.description}</div>
                </div>
              </div>

              {/* 处理记录 */}
              <div style={{ padding: 16, backgroundColor: '#FAFAFA', borderRadius: 8, marginBottom: 16, border: '1px solid #F0F0F0' }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>处理记录</h4>
                {processRecords.map((r, i) => (
                  <div key={i} style={{ display: 'flex', gap: 12, paddingBottom: 12, marginBottom: 12, borderBottom: i < processRecords.length - 1 ? '1px solid #F0F0F0' : 'none' }}>
                    <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: '#4a7c59', marginTop: 6, flexShrink: 0 }} />
                    <div style={{ fontSize: 13 }}>
                      <div style={{ fontWeight: 500, marginBottom: 4 }}>{r.action}</div>
                      <div style={{ color: 'rgba(0,0,0,0.45)' }}>{r.note}</div>
                      <div style={{ color: 'rgba(0,0,0,0.35)', marginTop: 4 }}>{r.date} · {r.operator}</div>
                    </div>
                  </div>
                ))}
              </div>

              {/* 板卡更换记录 */}
              <div style={{ padding: 16, backgroundColor: '#FAFAFA', borderRadius: 8, border: '1px solid #F0F0F0' }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>板卡更换记录</h4>
                {boardReplacementRecords.map((r, i) => (
                  <div key={i} style={{ fontSize: 13, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                    <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>类型：</span>{r.type} ({r.model})</div>
                    <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>更换时间：</span>{r.date}</div>
                    <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>原板卡：</span>{r.oldBoard}</div>
                    <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>新板卡：</span>{r.newBoard}</div>
                    <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>操作人：</span>{r.operator}</div>
                  </div>
                ))}
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setDetailDrawer(null)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>关闭</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
