'use client'
import { useState, useMemo } from 'react'
import Link from 'next/link'
import { Search, ChevronLeft, ChevronRight, Plus, Download, Info, Eye, X, Tag } from 'lucide-react'

const boardCardsData = [
  { id: 1, sn: 'MB25011500', type: '主协板', model: 'MB-V2.1', firmware: 'v2.1', status: '在库', deviceSn: '-', productionDate: '2025-01-15', calibStatus: '-', calibDate: '-'},
  { id: 2, sn: 'MCB-3000-20250118002', type: '主协板', model: 'MCB-3000', firmware: 'v2.1.0', status: '已装配', deviceSn: 'GD30-2025-000001', productionDate: '2025-01-18', calibStatus: '-', calibDate: '-', },
  { id: 3, sn: 'ACB-6000-20250110001', type: '采集板', model: 'ACB-6000', firmware: 'v3.0.2', status: '已装配', deviceSn: 'GD30-2025-000001', productionDate: '2025-01-10', calibStatus: '合格', calibDate: '2025-01-12'},
  { id: 4, sn: 'ACB-6000-20250110002', type: '采集板', model: 'ACB-6000', firmware: 'v3.0.2', status: '已装配', deviceSn: 'GD30-2025-000001', productionDate: '2025-01-10', calibStatus: '合格', calibDate: '2025-01-12'},
  { id: 5, sn: 'ACB-6000-20250112003', type: '采集板', model: 'ACB-6000', firmware: 'v3.0.2', status: '在库', deviceSn: '-', productionDate: '2025-01-12', calibStatus: '待校准', calibDate: '-', },
  { id: 6, sn: 'ACB-5000-20241205001', type: '采集板', model: 'ACB-5000', firmware: 'v2.5.1', status: '已装配', deviceSn: 'GD20-2024-000045', productionDate: '2024-12-05', calibStatus: '合格', calibDate: '2024-12-08'},
  { id: 7, sn: 'TXB-1000-20250120001', type: '发射板', model: 'TXB-1000', firmware: 'v1.2.0', status: '已装配', deviceSn: 'GD30-2025-000001', productionDate: '2025-01-20', calibStatus: '-', calibDate: '-'},
  { id: 8, sn: 'TXB-1000-20250122002', type: '发射板', model: 'TXB-1000', firmware: 'v1.2.0', status: '在库', deviceSn: '-', productionDate: '2025-01-22', calibStatus: '-', calibDate: '-'},
  { id: 9, sn: 'BST-500-20250201001', type: '升压板', model: 'BST-500', firmware: 'v1.1.0', status: '已装配', deviceSn: 'GD30-2025-000002', productionDate: '2025-02-01', calibStatus: '-', calibDate: '-'},
  { id: 10, sn: 'BST-500-20250203002', type: '升压板', model: 'BST-500', firmware: 'v1.1.0', status: '在库', deviceSn: '-', productionDate: '2025-02-03', calibStatus: '-', calibDate: '-'},
  { id: 11, sn: 'ACB-6000-20241120001', type: '采集板', model: 'ACB-6000', firmware: 'v3.0.2', status: '故障', deviceSn: '-', productionDate: '2024-11-20', calibStatus: '不合格', calibDate: '2025-02-10'},
  { id: 12, sn: 'MCB-2000-20240915001', type: '主协板', model: 'MCB-2000', firmware: 'v1.8.5', status: '已装配', deviceSn: 'GD20-2024-000046', productionDate: '2024-09-15', calibStatus: '-', calibDate: '-'},
  { id: 13, sn: 'ACB-6000-20250305001', type: '采集板', model: 'ACB-6000', firmware: 'v3.0.2', status: '在库', deviceSn: '-', productionDate: '2025-03-05', calibStatus: '待校准', calibDate: '-'},
  { id: 14, sn: 'TXB-800-20240610001', type: '发射板', model: 'TXB-800', firmware: 'v1.0.3', status: '报废', deviceSn: '-', productionDate: '2024-06-10', calibStatus: '-', calibDate: '-'},
]

const typeOptions = ['全部', '主协板', '采集板', '发射板', '升压板']
const statusOptions = ['全部', '在库', '已装配', '故障', '报废']
const calibStatusOptions = ['全部', '合格', '不合格', '待校准']

function getStatusStyle(status: string) {
  switch (status) {
    case '在库': return { backgroundColor: '#E6F7FF', color: '#1890FF', border: '1px solid #91D5FF' }
    case '已装配': return { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' }
    case '故障': return { backgroundColor: '#FFF1F0', color: '#FF4D4F', border: '1px solid #FFCCC7' }
    case '报废': return { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)', border: '1px solid #D9D9D9' }
    default: return { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)', border: '1px solid #D9D9D9' }
  }
}

function getCalibStyle(status: string) {
  switch (status) {
    case '合格': return { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' }
    case '不合格': return { backgroundColor: '#FFF1F0', color: '#FF4D4F', border: '1px solid #FFCCC7' }
    case '待校准': return { backgroundColor: '#FFFBE6', color: '#FAAD14', border: '1px solid #FFE58F' }
    default: return {}
  }
}

export default function BoardCardsPage() {
  const [filterType, setFilterType] = useState('全部')
  const [filterStatus, setFilterStatus] = useState('全部')
  const [filterCalib, setFilterCalib] = useState('全部')
  const [searchText, setSearchText] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [detailDrawer, setDetailDrawer] = useState<typeof boardCardsData[0] | null>(null)
  const pageSize = 8

  const filtered = useMemo(() => boardCardsData.filter(b => {
    if (filterType !== '全部' && b.type !== filterType) return false
    if (filterStatus !== '全部' && b.status !== filterStatus) return false
    if (filterCalib !== '全部' && b.calibStatus !== filterCalib) return false
    if (searchText && !b.sn.toLowerCase().includes(searchText.toLowerCase()) && !b.deviceSn.toLowerCase().includes(searchText.toLowerCase())) return false
    return true
  }), [filterType, filterStatus, filterCalib, searchText])

  const totalPages = Math.ceil(filtered.length / pageSize)
  const paged = filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize)

  // 统计
  const stats = useMemo(() => ({
    total: boardCardsData.length,
    inStock: boardCardsData.filter(b => b.status === '在库').length,
    assembled: boardCardsData.filter(b => b.status === '已装配').length,
    faulty: boardCardsData.filter(b => b.status === '故障').length,
    pendingCalib: boardCardsData.filter(b => b.calibStatus === '待校准').length,
  }), [])

  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 style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>
            <Download size={16} />导出
          </button>
          <Link href="/calibration/register" style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14, textDecoration: 'none' }}>
            <Plus size={16} />登记板卡
          </Link>
        </div>
      </div>

      {/* Stats Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 16, marginBottom: 24 }}>
        {[
          { label: '板卡总数', value: stats.total, color: '#4a7c59', bg: '#eef5f0' },
          { label: '在库', value: stats.inStock, color: '#1890FF', bg: '#E6F7FF' },
          { label: '已装配', value: stats.assembled, color: '#52C41A', bg: '#F6FFED' },
          { label: '故障', value: stats.faulty, color: '#FF4D4F', bg: '#FFF1F0' },
          { label: '待校准', value: stats.pendingCalib, color: '#FAAD14', bg: '#FFFBE6' },
        ].map(s => (
          <div key={s.label} style={{ backgroundColor: '#fff', borderRadius: 8, padding: 16, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
            <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)', marginBottom: 8 }}>{s.label}</div>
            <div style={{ fontSize: 24, fontWeight: 600, color: s.color }}>{s.value}</div>
          </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={filterType} onChange={e => { setFilterType(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
              {typeOptions.map(t => <option key={t} value={t}>{t}</option>)}
            </select>
          </div>
          <div style={{ flex: 1 }}>
            <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>板卡状态</label>
            <select value={filterStatus} onChange={e => { setFilterStatus(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
              {statusOptions.map(s => <option key={s} value={s}>{s}</option>)}
            </select>
          </div>
          <div style={{ flex: 1 }}>
            <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>校准状态</label>
            <select value={filterCalib} onChange={e => { setFilterCalib(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
              {calibStatusOptions.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>
          <div style={{ flex: 1 }}>
            <label style={{ display: 'block', fontSize: 13, color: 'rgba(0,0,0,0.65)', marginBottom: 6 }}>SN / 设备SN</label>
            <input type="text" value={searchText} onChange={e => { setSearchText(e.target.value); setCurrentPage(1) }} placeholder="搜索板卡SN或设备SN" 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' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ backgroundColor: '#FAFAFA' }}>
              {['板卡SN', '类型', '型号', '固件', '状态', '所属设备', '校准状态', '操作'].map(h => (
                <th key={h} style={{ padding: '12px 14px', textAlign: 'left', fontSize: 13, fontWeight: 600, color: 'rgba(0,0,0,0.85)', borderBottom: '1px solid #F0F0F0', whiteSpace: 'nowrap' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {paged.map(row => (
              <tr key={row.id} style={{ borderBottom: '1px solid #F0F0F0' }}>
                <td style={{ padding: '12px 14px', fontSize: 13, fontWeight: 500 }}>{row.sn}</td>
                <td style={{ padding: '12px 14px', fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>{row.type}</td>
                <td style={{ padding: '12px 14px', fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>{row.model}</td>
                <td style={{ padding: '12px 14px', fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>{row.firmware}</td>
                <td style={{ padding: '12px 14px' }}>
                  <span style={{ ...getStatusStyle(row.status), padding: '2px 8px', borderRadius: 4, fontSize: 12 }}>{row.status}</span>
                </td>
                <td style={{ padding: '12px 14px', fontSize: 13, color: row.deviceSn === '-' ? 'rgba(0,0,0,0.25)' : '#4a7c59', fontWeight: row.deviceSn === '-' ? 400 : 500 }}>{row.deviceSn}</td>
                <td style={{ padding: '12px 14px' }}>
                  {row.calibStatus !== '-' ? (
                    <span style={{ ...getCalibStyle(row.calibStatus), padding: '2px 8px', borderRadius: 4, fontSize: 12 }}>{row.calibStatus}</span>
                  ) : (
                    <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.25)' }}>-</span>
                  )}
                </td>
                <td style={{ padding: '12px 14px' }}>
                  <button onClick={() => setDetailDrawer(row)} style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <Eye size={14} />详情
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {/* Pagination */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px', borderTop: '1px solid #F0F0F0' }}>
          <span style={{ fontSize: 14, color: 'rgba(0,0,0,0.45)' }}>
            显示 {filtered.length > 0 ? (currentPage - 1) * pageSize + 1 : 0}-{Math.min(currentPage * pageSize, filtered.length)} / 共 {filtered.length} 条
          </span>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <button onClick={() => setCurrentPage(p => Math.max(1, p - 1))} disabled={currentPage === 1} style={{ padding: '4px 8px', border: '1px solid #D9D9D9', borderRadius: 4, backgroundColor: '#fff', cursor: currentPage === 1 ? 'not-allowed' : 'pointer', opacity: currentPage === 1 ? 0.4 : 1 }}><ChevronLeft size={16} /></button>
            {Array.from({ length: totalPages }, (_, i) => (
              <button key={i} onClick={() => setCurrentPage(i + 1)} style={{ width: 32, height: 32, borderRadius: 4, fontSize: 14, border: currentPage === i + 1 ? '1px solid #4a7c59' : '1px solid #D9D9D9', color: currentPage === i + 1 ? '#4a7c59' : 'rgba(0,0,0,0.65)', backgroundColor: currentPage === i + 1 ? '#eef5f0' : '#fff', cursor: 'pointer' }}>{i + 1}</button>
            ))}
            <button onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))} disabled={currentPage === totalPages || totalPages === 0} style={{ padding: '4px 8px', border: '1px solid #D9D9D9', borderRadius: 4, backgroundColor: '#fff', cursor: currentPage === totalPages || totalPages === 0 ? 'not-allowed' : 'pointer', opacity: currentPage === totalPages || totalPages === 0 ? 0.4 : 1 }}><ChevronRight size={16} /></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: 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={() => 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, marginTop: 0 }}>基本信息</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>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>板卡类型：</span>{detailDrawer.type}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>型号：</span>{detailDrawer.model}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>固件版本：</span>{detailDrawer.firmware}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>生产日期：</span>{detailDrawer.productionDate}</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>
              </div>

              {/* 装配信息 */}
              <div style={{ padding: 16, backgroundColor: '#FAFAFA', borderRadius: 8, marginBottom: 16, border: '1px solid #F0F0F0' }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12, marginTop: 0 }}>装配信息</h4>
                <div style={{ fontSize: 13 }}>
                  <span style={{ color: 'rgba(0,0,0,0.45)' }}>所属设备：</span>
                  {detailDrawer.deviceSn === '-' ? (
                    <span style={{ color: 'rgba(0,0,0,0.25)' }}>未装配</span>
                  ) : (
                    <span style={{ color: '#4a7c59', fontWeight: 500 }}>{detailDrawer.deviceSn}</span>
                  )}
                </div>
              </div>

              {/* 校准信息 */}
              {(detailDrawer.type === '采集板') && (
                <div style={{ padding: 16, backgroundColor: '#FAFAFA', borderRadius: 8, marginBottom: 16, border: '1px solid #F0F0F0' }}>
                  <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12, marginTop: 0 }}>校准信息</h4>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, fontSize: 13 }}>
                    <div>
                      <span style={{ color: 'rgba(0,0,0,0.45)' }}>校准状态：</span>
                      {detailDrawer.calibStatus !== '-' ? (
                        <span style={{ ...getCalibStyle(detailDrawer.calibStatus), padding: '1px 6px', borderRadius: 4, fontSize: 12 }}>{detailDrawer.calibStatus}</span>
                      ) : (
                        <span style={{ color: 'rgba(0,0,0,0.25)' }}>-</span>
                      )}
                    </div>
                    <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>校准日期：</span>{detailDrawer.calibDate}</div>
                  </div>
                </div>
              )}
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end' }}>
              <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>
  )
}
