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

interface FirmwareItem {
  id: number; version: string; board_version: string; type: string; date: string; status: string
  size: string; downloads: number; hw_range: string; upgrade_type: string; signed: number
  md5: string; sha256: string; notes: string[]; model_code: string
}
interface CategoryItem { id: number; name: string; has_firmware: number; status: string }

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 typeParam = searchParams.get('type') || ''
  const boardParam = searchParams.get('board') || ''
  const isFromType = !!typeParam
  const isFromBoard = !!boardParam

  const { data: categories } = useApi<CategoryItem[]>('/api/material-categories', [])
  const firmwareTabs = categories.filter(c => c.has_firmware && c.status === '启用').map(c => c.name)

  const [filterType, setFilterType] = useState(typeParam || '全部')
  const [firmwareList, setFirmwareList] = useState<FirmwareItem[]>([])
  const [loading, setLoading] = useState(true)
  const [expandedId, setExpandedId] = useState<number | null>(null)
  const [uploadOpen, setUploadOpen] = useState(false)
  const [uploadForm, setUploadForm] = useState({ version: '', hwRange: '', upgradeType: '可选', firmwareType: typeParam || '', signed: false, size: '', notes: '' })

  const fetchFirmware = useCallback(async () => {
    setLoading(true)
    let url = '/api/firmware'
    if (isFromBoard) url += `?board=${boardParam}`
    else if (isFromType) url += `?type=${typeParam}`
    else if (filterType !== '全部') url += `?type=${filterType}`
    const res = await fetch(url)
    setFirmwareList(await res.json())
    setLoading(false)
  }, [filterType, typeParam, boardParam, isFromType, isFromBoard])

  useEffect(() => { fetchFirmware() }, [fetchFirmware])

  const handleUpload = async () => {
    const fwType = isFromType ? typeParam : (uploadForm.firmwareType || '')
    if (!fwType || fwType === '全部') return
    await fetch('/api/firmware', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        version: uploadForm.version, type: fwType,
        hw_range: uploadForm.hwRange, upgrade_type: uploadForm.upgradeType,
        signed: uploadForm.signed, size: uploadForm.size, status: '草稿',
        notes: uploadForm.notes.split('\n').filter(Boolean),
      })
    })
    fetchFirmware(); setUploadOpen(false)
    setUploadForm({ version: '', hwRange: '', upgradeType: '可选', firmwareType: typeParam || '', signed: false, size: '', notes: '' })
  }

  const pageTitle = isFromType ? `固件库 — ${typeParam}` : isFromBoard ? `固件库 — ${boardParam}` : '固件库'

  return (
    <div style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {(isFromType || isFromBoard) && (
            <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>

      {/* Tabs — 仅通用模式显示 */}
      {!isFromType && !isFromBoard && firmwareTabs.length > 0 && (
        <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' }}>
            {['全部', ...firmwareTabs].map(tab => (
              <button key={tab} onClick={() => { setFilterType(tab); setExpandedId(null) }} style={{
                padding: '10px 20px', fontSize: 14, cursor: 'pointer', border: 'none', backgroundColor: 'transparent',
                borderBottom: filterType === tab ? '2px solid #4a7c59' : '2px solid transparent',
                color: filterType === tab ? '#4a7c59' : 'rgba(0,0,0,0.65)', fontWeight: filterType === tab ? 600 : 400,
              }}>{tab}</button>
            ))}
          </div>
        </div>
      )}

      {/* Firmware Cards */}
      {loading ? <div style={{ padding: 24 }}>加载中...</div> : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {firmwareList.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>
                      </div>
                      <div style={{ display: 'flex', gap: 24, fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>
                        <span>发布日期：{fw.date}</span>
                        {fw.size && <span>文件大小：{fw.size}</span>}
                        <span>下载次数：{fw.downloads.toLocaleString()}次</span>
                        <span>升级类型：<span style={{ color: fw.upgrade_type === '强制' ? '#FF4D4F' : '#4a7c59' }}>{fw.upgrade_type}</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>
                {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.hw_range || '-'}</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 }}>{fw.board_version || '-'}</div></div>
                      </div>
                    </div>
                    {fw.md5 && <div style={{ marginBottom: 12 }}><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>}
                    {fw.sha256 && <div style={{ marginBottom: 12 }}><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>}
                    {fw.notes.length > 0 && (
                      <div><div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)', marginBottom: 8 }}>发布说明</div>
                        <ul style={{ margin: 0, paddingLeft: 20 }}>{fw.notes.map((n, i) => <li key={i} style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 4 }}>{n}</li>)}</ul>
                      </div>
                    )}
                  </div>
                )}
              </div>
            )
          })}
          {firmwareList.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>
                  {isFromType ? (
                    <div style={{ padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, backgroundColor: '#FAFAFA' }}>{typeParam}</div>
                  ) : (
                    <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 }}>
                      <option value="">请选择</option>
                      {firmwareTabs.map(t => <option key={t} value={t}>{t}</option>)}
                    </select>
                  )}
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                <div>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>硬件版本范围</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>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>升级类型</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>
              <div style={{ marginBottom: 16 }}>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>文件大小</label>
                <input value={uploadForm.size} onChange={e => setUploadForm({ ...uploadForm, size: e.target.value })} placeholder="如 12.5MB" 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: '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 }}>固件包</label>
                <div style={{ border: '2px dashed #D9D9D9', borderRadius: 8, padding: '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>
              </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="修复XX问题&#10;新增XX功能" 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={handleUpload} disabled={!uploadForm.version || (!isFromType && !uploadForm.firmwareType)} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: (uploadForm.version && (isFromType || uploadForm.firmwareType)) ? '#4a7c59' : '#D9D9D9', color: '#fff', cursor: (uploadForm.version && (isFromType || uploadForm.firmwareType)) ? 'pointer' : 'not-allowed', fontSize: 14 }}>上传</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
