'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Plus, X, Edit, Trash2, Info, Upload, RefreshCw } from 'lucide-react'
import { useApi } from '@/lib/hooks'

interface MaterialType {
  id: number; name: string; category: string; deviceModels: string[]; description: string; status: string
}
interface MaterialVersion {
  id: number; type: string; version: string; status: string
}

interface CategoryItem { id: number; name: string; status: string; has_firmware: number }
interface DeviceModel { id: number; name: string; code: string; status: string }

function getStatusStyle(status: string) {
  switch (status) {
    case '启用': case '在产': return { backgroundColor: '#eef5f0', color: '#4a7c59', border: '1px solid #a3c4ad' }
    case '停用': case '停产': return { backgroundColor: '#FFFBE6', color: '#FAAD14', border: '1px solid #FFE58F' }
    default: return { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)', border: '1px solid #D9D9D9' }
  }
}

export default function MaterialsManagePage() {
  const router = useRouter()
  const { data: materialTypes, loading: lt, refetch: refetchTypes } = useApi<MaterialType[]>('/api/material-types', [])
  const { data: versionsData, loading: lv, refetch: refetchVersions } = useApi<MaterialVersion[]>('/api/material-versions', [])
  const { data: categoriesData } = useApi<CategoryItem[]>('/api/material-categories', [])
  const { data: deviceModelsData } = useApi<DeviceModel[]>('/api/models', [])
  const categoryOptions = ['全部', ...categoriesData.filter(c => c.status === '启用').map(c => c.name)]
  const deviceModelOptions = deviceModelsData.map(dm => dm.name)

  const [filterCategory, setFilterCategory] = useState('全部')
  const [searchText, setSearchText] = useState('')
  const [addDrawer, setAddDrawer] = useState(false)
  const [editDrawer, setEditDrawer] = useState<MaterialType | null>(null)
  const [typeForm, setTypeForm] = useState({ name: '', category: '主协板', deviceModels: [] as string[], description: '', status: '启用' })
  // Expanded row to show versions
  const [versionDrawer, setVersionDrawer] = useState<MaterialType | null>(null)
  // Add version inline
  const [addVersionFor, setAddVersionFor] = useState<string | null>(null)
  const [newVersion, setNewVersion] = useState('')

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

  const filtered = materialTypes.filter(bt => {
    if (filterCategory !== '全部' && bt.category !== filterCategory) return false
    if (searchText && !bt.name.toLowerCase().includes(searchText.toLowerCase()) && !bt.description.toLowerCase().includes(searchText.toLowerCase())) return false
    return true
  })

  // Group versions by category
  const versionsByCategory = (category: string) => versionsData.filter(v => v.type === category)

  const handleAddType = async () => {
    await fetch('/api/material-types', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(typeForm) })
    refetchTypes(); setAddDrawer(false)
    setTypeForm({ name: '', category: categoryOptions.find(c => c !== '全部') || '', deviceModels: [], description: '', status: '启用' })
  }
  const handleEditType = async () => {
    if (!editDrawer) return
    await fetch('/api/material-types', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(editDrawer) })
    refetchTypes(); setEditDrawer(null)
  }
  const handleDeleteType = async (id: number) => {
    await fetch('/api/material-types', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) })
    refetchTypes()
  }
  const toggleDeviceModel = (model: string, target: 'add' | 'edit') => {
    if (target === 'add') {
      setTypeForm(prev => ({ ...prev, deviceModels: prev.deviceModels.includes(model) ? prev.deviceModels.filter(m => m !== model) : [...prev.deviceModels, model] }))
    } else if (editDrawer) {
      setEditDrawer({ ...editDrawer, deviceModels: editDrawer.deviceModels.includes(model) ? editDrawer.deviceModels.filter(m => m !== model) : [...editDrawer.deviceModels, model] })
    }
  }
  const handleToggleVersionStatus = async (id: number) => {
    const v = versionsData.find(b => b.id === id)
    if (!v) return
    await fetch('/api/material-versions', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, status: v.status === '在产' ? '停产' : '在产' }) })
    refetchVersions()
  }
  const handleAddVersion = async (category: string) => {
    if (!newVersion.trim()) return
    await fetch('/api/material-versions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: category, version: newVersion, status: '在产' }) })
    refetchVersions(); setAddVersionFor(null); setNewVersion('')
  }

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 24 }}>
        <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', alignItems: 'flex-start', gap: 12, padding: 16, backgroundColor: '#eef5f0', borderRadius: 8, marginBottom: 24, border: '1px solid #a3c4ad' }}>
        <Info size={18} style={{ color: '#4a7c59', flexShrink: 0, marginTop: 2 }} />
        <div style={{ fontSize: 14, color: '#4a7c59', lineHeight: 1.6 }}>物料类型定义了物料与设备型号的关联关系。点击行可展开查看和管理该分类下的物料版本。</div>
      </div>

      {/* Filter */}
      <div style={{ backgroundColor: '#fff', borderRadius: 8, padding: 20, marginBottom: 24, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16 }}>
          <div style={{ flex: 1 }}>
            <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>物料分类</label>
            <select value={filterCategory} onChange={e => setFilterCategory(e.target.value)} style={{ width: '100%', padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
              {categoryOptions.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>
          <div style={{ flex: 2 }}>
            <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>搜索</label>
            <input type="text" value={searchText} onChange={e => setSearchText(e.target.value)} placeholder="搜索类型名称或描述" style={{ width: '100%', padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
          </div>
        </div>
      </div>

      {/* Table */}
      <div style={{ backgroundColor: '#fff', borderRadius: 8, boxShadow: '0 1px 2px rgba(0,0,0,0.05)', overflow: 'hidden' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid #F0F0F0' }}>
          <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>物料列表（共 {filtered.length} 项）</h3>
          <button onClick={() => { setTypeForm({ name: '', category: categoryOptions.find(c => c !== '全部') || '', deviceModels: [], description: '', status: '启用' }); setAddDrawer(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>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr style={{ backgroundColor: '#FAFAFA' }}>
            {['物料名称', '物料分类', '适配设备型号', '版本', '描述', '状态', '操作'].map(h => (
              <th key={h} style={{ padding: '12px 16px', textAlign: 'left', fontSize: 13, fontWeight: 600, color: 'rgba(0,0,0,0.85)', borderBottom: '1px solid #F0F0F0' }}>{h}</th>
            ))}
          </tr></thead>
          <tbody>
            {filtered.map(bt => {
              const versions = versionsByCategory(bt.category)
              return (
                <tr key={bt.id} style={{ borderBottom: '1px solid #F0F0F0' }}>
                  <td style={{ padding: '12px 16px', fontSize: 14, fontWeight: 500 }}>{bt.name}</td>
                  <td style={{ padding: '12px 16px', fontSize: 14, color: 'rgba(0,0,0,0.65)' }}>{bt.category}</td>
                  <td style={{ padding: '12px 16px' }}>
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      {bt.deviceModels.map(dm => (<span key={dm} style={{ padding: '2px 8px', borderRadius: 4, fontSize: 12, backgroundColor: '#F0F5FF', color: '#597EF7', border: '1px solid #ADC6FF' }}>{dm}</span>))}
                    </div>
                  </td>
                  <td style={{ padding: '12px 16px' }}>
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
                      {versions.map(v => (
                        <span key={v.id} style={{ padding: '2px 8px', borderRadius: 4, fontSize: 12, ...getStatusStyle(v.status) }}>{v.version}</span>
                      ))}
                      {versions.length === 0 && <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.25)' }}>暂无版本</span>}
                      <button onClick={() => setVersionDrawer(bt)} style={{ padding: '1px 6px', borderRadius: 4, fontSize: 11, border: '1px solid #D9D9D9', backgroundColor: '#fff', color: 'rgba(0,0,0,0.45)', cursor: 'pointer' }}>管理</button>
                    </div>
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>{bt.description}</td>
                  <td style={{ padding: '12px 16px' }}><span style={{ ...getStatusStyle(bt.status), padding: '2px 8px', borderRadius: 4, fontSize: 12 }}>{bt.status}</span></td>
                  <td style={{ padding: '12px 16px' }}>
                    <div style={{ display: 'flex', gap: 12 }}>
                      <button onClick={() => setEditDrawer({ ...bt })} style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13, display: 'flex', alignItems: 'center', gap: 4 }}><Edit size={14} />编辑</button>
                      {categoriesData.find(c => c.name === bt.category)?.has_firmware ? (
                        <button onClick={() => router.push(`/firmware?type=${bt.category}`)} style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13, display: 'flex', alignItems: 'center', gap: 4 }}><Upload size={14} />固件</button>
                      ) : null}
                      <button onClick={() => handleDeleteType(bt.id)} style={{ color: '#FF4D4F', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13, display: 'flex', alignItems: 'center', gap: 4 }}><Trash2 size={14} />删除</button>
                    </div>
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>

        {/* Version Management Drawer */}
        {versionDrawer && (() => {
          const category = versionDrawer.category
          const versions = versionsByCategory(category)
          const gdModels = ['GD-30 Supreme', 'GD-20 Supreme', 'GD-10 Supreme']
          const firmwareCategories = ['采集板', '主协板', '发射板']
          const hasFirmware = firmwareCategories.includes(category) && versionDrawer.deviceModels.some(dm => gdModels.includes(dm))
          return (
            <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
              <div onClick={() => setVersionDrawer(null)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
              <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 560, 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 }}>{versionDrawer.name} — 版本管理</h3>
                  <button onClick={() => setVersionDrawer(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: 20, border: '1px solid #F0F0F0' }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 13 }}>
                      <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>物料分类：</span>{category}</div>
                      <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>状态：</span><span style={{ ...getStatusStyle(versionDrawer.status), padding: '1px 6px', borderRadius: 4, fontSize: 12 }}>{versionDrawer.status}</span></div>
                      <div style={{ gridColumn: '1 / -1' }}><span style={{ color: 'rgba(0,0,0,0.45)' }}>适配型号：</span>{versionDrawer.deviceModels.join('、')}</div>
                    </div>
                  </div>

                  {/* 添加版本 */}
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                    <h4 style={{ fontSize: 14, fontWeight: 600, margin: 0 }}>版本列表</h4>
                    <button onClick={() => { setAddVersionFor(category); setNewVersion('') }} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '4px 12px', border: '1px solid #4a7c59', borderRadius: 6, backgroundColor: '#fff', color: '#4a7c59', cursor: 'pointer', fontSize: 13 }}><Plus size={14} />添加版本</button>
                  </div>
                  {addVersionFor === category && (
                    <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
                      <input value={newVersion} onChange={e => setNewVersion(e.target.value)} placeholder="输入版本号，如 MB-V3.0" style={{ flex: 1, padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 13, boxSizing: 'border-box' }} />
                      <button onClick={() => handleAddVersion(category)} style={{ padding: '6px 16px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 13 }}>确定</button>
                      <button onClick={() => setAddVersionFor(null)} style={{ padding: '6px 16px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 13 }}>取消</button>
                    </div>
                  )}

                  {/* 版本表格 */}
                  {versions.length > 0 ? (
                    <table style={{ width: '100%', borderCollapse: 'collapse', backgroundColor: '#fff', borderRadius: 6, overflow: 'hidden', border: '1px solid #F0F0F0' }}>
                      <thead><tr style={{ backgroundColor: '#F5F5F5' }}>
                        {['版本', '状态', '操作'].map(h => (<th key={h} style={{ padding: '10px 14px', textAlign: 'left', fontSize: 12, fontWeight: 600, color: 'rgba(0,0,0,0.65)', borderBottom: '1px solid #F0F0F0' }}>{h}</th>))}
                      </tr></thead>
                      <tbody>
                        {versions.map(v => (
                          <tr key={v.id} style={{ borderBottom: '1px solid #F0F0F0' }}>
                            <td style={{ padding: '10px 14px', fontSize: 13, fontWeight: 500 }}>{v.version}</td>
                            <td style={{ padding: '10px 14px' }}><span style={{ ...getStatusStyle(v.status), padding: '2px 8px', borderRadius: 4, fontSize: 11 }}>{v.status}</span></td>
                            <td style={{ padding: '10px 14px' }}>
                              <div style={{ display: 'flex', gap: 12 }}>
                                <button onClick={() => handleToggleVersionStatus(v.id)} style={{ color: v.status === '在产' ? '#FAAD14' : '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 12, display: 'flex', alignItems: 'center', gap: 4 }}><RefreshCw size={12} />{v.status === '在产' ? '停产' : '恢复'}</button>
                                {hasFirmware ? (
                                  <button onClick={() => router.push(`/firmware?board=${v.version}`)} style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 12, display: 'flex', alignItems: 'center', gap: 4 }}><Upload size={12} />固件管理</button>
                                ) : (
                                  <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.15)', display: 'flex', alignItems: 'center', gap: 4, cursor: 'not-allowed' }}><Upload size={12} />固件管理</span>
                                )}
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  ) : (
                    <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.25)', textAlign: 'center', padding: 24, backgroundColor: '#FAFAFA', borderRadius: 8, border: '1px solid #F0F0F0' }}>暂无版本，点击上方按钮添加</div>
                  )}

                  {/* 固件说明 */}
                  {!hasFirmware && (
                    <div style={{ marginTop: 16, padding: 12, backgroundColor: '#FFFBE6', borderRadius: 6, border: '1px solid #FFE58F', fontSize: 12, color: '#FAAD14', display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Info size={14} />
                      <span>该物料类型不支持固件管理（仅 GD-10/20/30 的主协板、采集板、发射板支持）</span>
                    </div>
                  )}
                </div>
                <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end' }}>
                  <button onClick={() => setVersionDrawer(null)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>关闭</button>
                </div>
              </div>
            </div>
          )
        })()}
      </div>

      {/* Add Type Drawer */}
      {addDrawer && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setAddDrawer(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={() => setAddDrawer(false)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 物料名称</label>
                <input value={typeForm.name} onChange={e => setTypeForm({ ...typeForm, name: e.target.value })} placeholder="如 GD30 采集板" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 物料分类</label>
                <select value={typeForm.category} onChange={e => setTypeForm({ ...typeForm, category: e.target.value })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                  {categoryOptions.filter(c => c !== '全部').map(c => <option key={c} value={c}>{c}</option>)}
                </select>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 适配设备型号</label>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {deviceModelOptions.map(dm => (
                    <button key={dm} onClick={() => toggleDeviceModel(dm, 'add')} style={{ padding: '6px 14px', borderRadius: 6, fontSize: 13, cursor: 'pointer', border: typeForm.deviceModels.includes(dm) ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: typeForm.deviceModels.includes(dm) ? '#eef5f0' : '#fff', color: typeForm.deviceModels.includes(dm) ? '#4a7c59' : 'rgba(0,0,0,0.65)' }}>{dm}</button>
                  ))}
                </div>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>状态</label>
                <div style={{ display: 'flex', gap: 12 }}>
                  {['启用', '停用'].map(s => (
                    <button key={s} onClick={() => setTypeForm({ ...typeForm, status: s })} style={{ padding: '6px 20px', borderRadius: 6, fontSize: 14, cursor: 'pointer', border: typeForm.status === s ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: typeForm.status === s ? '#eef5f0' : '#fff', color: typeForm.status === s ? '#4a7c59' : 'rgba(0,0,0,0.65)' }}>{s}</button>
                  ))}
                </div>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>描述</label>
                <textarea value={typeForm.description} onChange={e => setTypeForm({ ...typeForm, description: e.target.value })} placeholder="物料类型描述" rows={3} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box', resize: 'vertical' }} />
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setAddDrawer(false)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={handleAddType} disabled={!typeForm.name || typeForm.deviceModels.length === 0} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: typeForm.name && typeForm.deviceModels.length > 0 ? '#4a7c59' : '#D9D9D9', color: '#fff', cursor: typeForm.name && typeForm.deviceModels.length > 0 ? 'pointer' : 'not-allowed', fontSize: 14 }}>保存</button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Type Drawer */}
      {editDrawer && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setEditDrawer(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 }}>编辑物料类型</h3>
              <button onClick={() => setEditDrawer(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={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 物料名称</label>
                <input value={editDrawer.name} onChange={e => setEditDrawer({ ...editDrawer, name: e.target.value })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 物料分类</label>
                <select value={editDrawer.category} onChange={e => setEditDrawer({ ...editDrawer, category: e.target.value })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                  {categoryOptions.filter(c => c !== '全部').map(c => <option key={c} value={c}>{c}</option>)}
                </select>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 适配设备型号</label>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {deviceModelOptions.map(dm => (
                    <button key={dm} onClick={() => toggleDeviceModel(dm, 'edit')} style={{ padding: '6px 14px', borderRadius: 6, fontSize: 13, cursor: 'pointer', border: editDrawer.deviceModels.includes(dm) ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: editDrawer.deviceModels.includes(dm) ? '#eef5f0' : '#fff', color: editDrawer.deviceModels.includes(dm) ? '#4a7c59' : 'rgba(0,0,0,0.65)' }}>{dm}</button>
                  ))}
                </div>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>描述</label>
                <textarea value={editDrawer.description} onChange={e => setEditDrawer({ ...editDrawer, description: e.target.value })} rows={3} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box', resize: 'vertical' }} />
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>状态</label>
                <div style={{ display: 'flex', gap: 12 }}>
                  {['启用', '停用'].map(s => (
                    <button key={s} onClick={() => setEditDrawer({ ...editDrawer, status: s })} style={{ padding: '6px 20px', borderRadius: 6, fontSize: 14, cursor: 'pointer', border: editDrawer.status === s ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: editDrawer.status === s ? '#eef5f0' : '#fff', color: editDrawer.status === s ? '#4a7c59' : 'rgba(0,0,0,0.65)' }}>{s}</button>
                  ))}
                </div>
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setEditDrawer(null)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={handleEditType} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>保存</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
