'use client'
import { useState, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { ArrowLeft, Upload, Download, ChevronDown, ChevronUp, X, Package, Shield, FileText } from 'lucide-react'

const firmwareTypes = ['全部', '主协板', '采集板', '发射板', '升压板', '主机固件', '计算单元固件']

const firmwareData = [
  { id: 1, version: 'v2.1.0', boardModel: 'MB25130025', type: '主协板', date: '2024-03-10', status: '已发布', size: '12.5MB', downloads: 1234, hwRange: 'MB25130025 Rev.A~C', upgradeType: '可选', signed: true, md5: 'a1b2c3d4e5f6...', sha256: '9f8e7d6c5b4a...', notes: ['修复通信协议兼容性问题', '优化低功耗模式切换', '新增看门狗超时配置'] },
  { id: 2, version: 'v2.0.0', boardModel: 'MB25130025', type: '主协板', date: '2024-01-15', status: '已发布', size: '11.8MB', downloads: 2456, hwRange: 'MB25130025 Rev.A~C', upgradeType: '强制', signed: true, md5: 'b2c3d4e5f6a1...', sha256: '8e7d6c5b4a9f...', notes: ['新增多通道采集支持', '重构通信协议栈'] },
  { id: 3, version: 'v1.8.5', boardModel: 'MCB-2000', type: '主协板', date: '2023-11-01', status: '已发布', size: '9.2MB', downloads: 3120, hwRange: 'MCB-2000 Rev.B~D', upgradeType: '可选', signed: true, md5: 'c3d4e5f6a1b2...', sha256: '7d6c5b4a9f8e...', notes: ['优化功耗管理', '修复偶发重启问题'] },
  { id: 4, version: 'v3.0.2', boardModel: 'ACB-6000', type: '采集板', date: '2024-02-20', status: '已发布', size: '8.7MB', downloads: 890, hwRange: 'ACB-6000 Rev.A~B', upgradeType: '可选', signed: true, md5: 'd4e5f6a1b2c3...', sha256: '6c5b4a9f8e7d...', notes: ['提升采样精度', '修复通道串扰问题', '新增自校准功能'] },
  { id: 5, version: 'v2.5.1', boardModel: 'ACB-5000', type: '采集板', date: '2023-09-15', status: '已发布', size: '7.1MB', downloads: 1567, hwRange: 'ACB-5000 Rev.A~C', upgradeType: '可选', signed: true, md5: 'e5f6a1b2c3d4...', sha256: '5b4a9f8e7d6c...', notes: ['优化ADC驱动', '修复温漂补偿算法'] },
  { id: 6, version: 'v1.2.0', boardModel: 'TXB-1000', type: '发射板', date: '2024-02-28', status: '已发布', size: '6.3MB', downloads: 456, hwRange: 'TXB-1000 Rev.A', upgradeType: '强制', signed: true, md5: 'f6a1b2c3d4e5...', sha256: '4a9f8e7d6c5b...', notes: ['新增过流保护', '优化PWM控制算法'] },
  { id: 7, version: 'v1.0.3', boardModel: 'TXB-800', type: '发射板', date: '2023-06-20', status: '已发布', size: '5.8MB', downloads: 789, hwRange: 'TXB-800 Rev.A~B', upgradeType: '可选', signed: false, md5: 'a1c3e5b2d4f6...', sha256: '3f8e6d4b2a9c...', notes: ['修复高压输出不稳定'] },
  { id: 8, version: 'v1.1.0', boardModel: 'BST-500', type: '升压板', date: '2024-04-01', status: '草稿', size: '4.2MB', downloads: 0, hwRange: 'BST-500 Rev.A', upgradeType: '可选', signed: false, md5: '-', sha256: '-', notes: ['初始版本', '支持500V~1500V输出'] },
  { id: 9, version: 'v0.9.8', boardModel: 'BST-300', type: '升压板', date: '2023-08-25', status: '已发布', size: '3.9MB', downloads: 345, hwRange: 'BST-300 Rev.A', upgradeType: '可选', signed: true, md5: 'b2d4f6a1c3e5...', sha256: '2a9c8e6d4b3f...', notes: ['修复过温保护阈值'] },
]

function getStatusStyle(status: string) {
  switch (status) {
    case '已发布': return { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' }
    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 FirmwarePage() {
  return (
    <Suspense fallback={<div style={{ padding: 24 }}>加载中...</div>}>
      <FirmwareContent />
    </Suspense>
  )
}

function FirmwareContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const boardParam = searchParams.get('board') || ''

  // Derive initial type filter from board param
  const matchedFw = boardParam ? firmwareData.find(f => f.boardModel === boardParam) : null
  const initialType = matchedFw ? matchedFw.type : '全部'

  const [filterType, setFilterType] = useState(initialType)
  const [filterBoard, setFilterBoard] = useState(boardParam)
  const [expandedId, setExpandedId] = useState<number | null>(null)
  const [uploadOpen, setUploadOpen] = useState(false)
  const [uploadForm, setUploadForm] = useState({ version: '', hwRange: '', upgradeType: '可选', firmwareType: '主协板', signed: false, notes: '' })

  const filtered = firmwareData.filter(f => {
    if (filterType !== '全部' && f.type !== filterType) return false
    if (filterBoard && f.boardModel !== filterBoard) return false
    return true
  })

  // Get unique board models for the current type filter
  const boardModels = [...new Set(
    firmwareData
      .filter(f => filterType === '全部' || f.type === filterType)
      .map(f => f.boardModel)
  )]

  const handleTypeChange = (type: string) => {
    setFilterType(type)
    setFilterBoard('')
  }

  const pageTitle = filterBoard
    ? `固件库 — ${filterBoard}`
    : '固件库'

  return (
    <div style={{ padding: 24 }}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {boardParam && (
            <button onClick={() => router.back()} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 32, height: 32, border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer' }}>
              <ArrowLeft size={16} />
            </button>
          )}
          <div>
            <h2 style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>{pageTitle}</h2>
            <p style={{ fontSize: 14, color: 'rgba(0,0,0,0.45)', margin: '4px 0 0' }}>管理固件版本，支持上传与下载</p>
          </div>
        </div>
        <button onClick={() => setUploadOpen(true)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>
          <Upload size={16} />上传固件
        </button>
      </div>

      {/* Type Tabs + Board Filter */}
      <div style={{ backgroundColor: '#fff', borderRadius: 8, marginBottom: 24, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
        <div style={{ display: 'flex', borderBottom: '1px solid #F0F0F0' }}>
          {firmwareTypes.map(type => (
            <button key={type} onClick={() => handleTypeChange(type)} style={{
              padding: '10px 20px', fontSize: 14, cursor: 'pointer', border: 'none', backgroundColor: 'transparent',
              borderBottom: filterType === type ? '2px solid #4a7c59' : '2px solid transparent',
              color: filterType === type ? '#4a7c59' : 'rgba(0,0,0,0.65)', fontWeight: filterType === type ? 600 : 400,
            }}>{type}</button>
          ))}
        </div>
        {boardModels.length > 1 && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '12px 20px' }}>
            <span style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)', flexShrink: 0 }}>板卡型号：</span>
            <button onClick={() => setFilterBoard('')} style={{ padding: '4px 12px', borderRadius: 4, fontSize: 13, cursor: 'pointer', border: !filterBoard ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: !filterBoard ? '#eef5f0' : '#fff', color: !filterBoard ? '#4a7c59' : 'rgba(0,0,0,0.65)' }}>全部</button>
            {boardModels.map(bm => (
              <button key={bm} onClick={() => setFilterBoard(bm)} style={{ padding: '4px 12px', borderRadius: 4, fontSize: 13, cursor: 'pointer', border: filterBoard === bm ? '1px solid #4a7c59' : '1px solid #D9D9D9', backgroundColor: filterBoard === bm ? '#eef5f0' : '#fff', color: filterBoard === bm ? '#4a7c59' : 'rgba(0,0,0,0.65)' }}>{bm}</button>
            ))}
          </div>
        )}
      </div>

      {/* Firmware Cards */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {filtered.map(fw => {
          const isExpanded = expandedId === fw.id
          return (
            <div key={fw.id} style={{ backgroundColor: '#fff', borderRadius: 8, boxShadow: '0 1px 2px rgba(0,0,0,0.05)', overflow: 'hidden' }}>
              <div style={{ padding: 20 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                      <span style={{ fontSize: 18, fontWeight: 600 }}>{fw.version}</span>
                      <span style={{ ...getStatusStyle(fw.status), padding: '2px 8px', borderRadius: 4, fontSize: 12 }}>{fw.status}</span>
                      <span style={{ padding: '2px 8px', borderRadius: 4, fontSize: 12, backgroundColor: '#F0F5FF', color: '#597EF7', border: '1px solid #ADC6FF' }}>{fw.type}</span>
                      <span style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)' }}>{fw.boardModel}</span>
                    </div>
                    <div style={{ display: 'flex', gap: 24, fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>
                      <span>发布日期：{fw.date}</span>
                      <span>文件大小：{fw.size}</span>
                      <span>下载次数：{fw.downloads.toLocaleString()}次</span>
                      <span>升级类型：<span style={{ color: fw.upgradeType === '强制' ? '#FF4D4F' : '#4a7c59' }}>{fw.upgradeType}</span></span>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 8, flexShrink: 0, marginLeft: 16 }}>
                    <button style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 13, color: '#4a7c59' }}>
                      <Download size={14} />下载
                    </button>
                    <button onClick={() => setExpandedId(isExpanded ? null : fw.id)} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>
                      {isExpanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
                      {isExpanded ? '收起' : '详情'}
                    </button>
                  </div>
                </div>
              </div>

              {/* Expanded Detail */}
              {isExpanded && (
                <div style={{ borderTop: '1px solid #F0F0F0', padding: 20, backgroundColor: '#FAFAFA' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16, marginBottom: 16 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Shield size={14} style={{ color: 'rgba(0,0,0,0.35)' }} />
                      <div>
                        <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)' }}>数字签名</div>
                        <div style={{ fontSize: 13 }}>{fw.signed ? '已签名' : '未签名'}</div>
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Package size={14} style={{ color: 'rgba(0,0,0,0.35)' }} />
                      <div>
                        <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)' }}>硬件版本范围</div>
                        <div style={{ fontSize: 13 }}>{fw.hwRange}</div>
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <FileText size={14} style={{ color: 'rgba(0,0,0,0.35)' }} />
                      <div>
                        <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)' }}>升级类型</div>
                        <div style={{ fontSize: 13, color: fw.upgradeType === '强制' ? '#FF4D4F' : '#4a7c59' }}>{fw.upgradeType}</div>
                      </div>
                    </div>
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)', marginBottom: 4 }}>MD5</div>
                    <div style={{ fontSize: 13, fontFamily: 'monospace', color: 'rgba(0,0,0,0.65)' }}>{fw.md5}</div>
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)', marginBottom: 4 }}>SHA256</div>
                    <div style={{ fontSize: 13, fontFamily: 'monospace', color: 'rgba(0,0,0,0.65)' }}>{fw.sha256}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)', marginBottom: 8 }}>发布说明</div>
                    <ul style={{ margin: 0, paddingLeft: 20 }}>
                      {fw.notes.map((note, i) => (
                        <li key={i} style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 4 }}>{note}</li>
                      ))}
                    </ul>
                  </div>
                </div>
              )}
            </div>
          )
        })}
        {filtered.length === 0 && (
          <div style={{ backgroundColor: '#fff', borderRadius: 8, padding: 60, textAlign: 'center', boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
            <div style={{ fontSize: 14, color: 'rgba(0,0,0,0.25)' }}>暂无固件版本</div>
          </div>
        )}
      </div>

      {/* Upload Dialog */}
      {uploadOpen && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div onClick={() => setUploadOpen(false)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'relative', width: 550, backgroundColor: '#fff', borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.15)' }}>
            <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={() => setUploadOpen(false)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ padding: 24 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                <div>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}><span style={{ color: '#FF4D4F' }}>*</span> 固件版本</label>
                  <input value={uploadForm.version} onChange={e => setUploadForm({ ...uploadForm, version: e.target.value })} placeholder="如 v2.4.0" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}><span style={{ color: '#FF4D4F' }}>*</span> 硬件版本范围</label>
                  <input value={uploadForm.hwRange} onChange={e => setUploadForm({ ...uploadForm, hwRange: e.target.value })} placeholder="如 MB25130025 Rev.A~C" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                <div>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}><span style={{ color: '#FF4D4F' }}>*</span> 升级类型</label>
                  <select value={uploadForm.upgradeType} onChange={e => setUploadForm({ ...uploadForm, upgradeType: e.target.value })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                    <option value="可选">可选</option>
                    <option value="强制">强制</option>
                  </select>
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}><span style={{ color: '#FF4D4F' }}>*</span> 固件类型</label>
                  <select value={uploadForm.firmwareType} onChange={e => setUploadForm({ ...uploadForm, firmwareType: 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>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, cursor: 'pointer' }}>
                  <input type="checkbox" checked={uploadForm.signed} onChange={e => setUploadForm({ ...uploadForm, signed: e.target.checked })} />
                  数字签名
                </label>
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}><span style={{ color: '#FF4D4F' }}>*</span> 固件包</label>
                <div style={{ border: '2px dashed #D9D9D9', borderRadius: 8, padding: '32px 24px', textAlign: 'center', cursor: 'pointer' }}>
                  <Upload size={24} style={{ color: 'rgba(0,0,0,0.25)', marginBottom: 8 }} />
                  <div style={{ fontSize: 14, color: 'rgba(0,0,0,0.45)' }}>点击或拖拽上传 ZIP 文件</div>
                  <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.25)', marginTop: 4 }}>支持 .zip 格式</div>
                </div>
              </div>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>发布说明</label>
                <textarea value={uploadForm.notes} onChange={e => setUploadForm({ ...uploadForm, notes: 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>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setUploadOpen(false)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={() => setUploadOpen(false)} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>上传</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
