'use client'
import { useState } from 'react'
import { Info, Search, Download, ChevronLeft, ChevronRight, X, Eye, FileDown } from 'lucide-react'

const calibrationData = [
  { id: 1, sn: 'RX20240308001', boardModel: 'ACB-6000', calibDate: '2024-03-01', expiryDate: '2025-03-01', operator: '王工程师', status: '合格', channel: 6, deviation: '±0.05%' },
  { id: 2, sn: 'RX20240308002', boardModel: 'ACB-6000', calibDate: '2024-02-15', expiryDate: '2025-02-15', operator: '张工程师', status: '合格', channel: 6, deviation: '±0.03%' },
  { id: 3, sn: 'RX20240115003', boardModel: 'ACB-5000', calibDate: '2024-01-15', expiryDate: '2025-01-15', operator: '王工程师', status: '合格', channel: 4, deviation: '±0.08%' },
  { id: 4, sn: 'RX20240420004', boardModel: 'ACB-6000', calibDate: '2024-04-20', expiryDate: '2025-04-20', operator: '李工程师', status: '待校准', channel: 6, deviation: '-' },
  { id: 5, sn: 'RX20231205005', boardModel: 'ACB-5000', calibDate: '2023-12-05', expiryDate: '2024-12-05', operator: '王工程师', status: '不合格', channel: 4, deviation: '±0.25%' },
  { id: 6, sn: 'RX20240610006', boardModel: 'ACB-6000', calibDate: '2024-06-10', expiryDate: '2025-06-10', operator: '张工程师', status: '合格', channel: 6, deviation: '±0.04%' },
  { id: 7, sn: 'RX20240801007', boardModel: 'ACB-6000', calibDate: '2024-08-01', expiryDate: '2025-08-01', operator: '李工程师', status: '待校准', channel: 6, deviation: '-' },
  { id: 8, sn: 'RX20240305008', boardModel: 'ACB-5000', calibDate: '2024-03-05', expiryDate: '2025-03-05', operator: '王工程师', status: '合格', channel: 4, deviation: '±0.06%' },
  { id: 9, sn: 'RX20240922009', boardModel: 'ACB-6000', calibDate: '2024-09-22', expiryDate: '2025-09-22', operator: '张工程师', status: '合格', channel: 6, deviation: '±0.02%' },
  { id: 10, sn: 'RX20231110010', boardModel: 'ACB-5000', calibDate: '2023-11-10', expiryDate: '2024-11-10', operator: '李工程师', status: '不合格', channel: 4, deviation: '±0.30%' },
]

const operatorOptions = ['全部', '王工程师', '张工程师', '李工程师']
const statusOptions = ['全部', '合格', '不合格', '待校准']

const calibDetailData = {
  basicInfo: { sn: 'RX20240308001', model: 'ACB-6000', channels: 6, productionDate: '2024-01-10' },
  calibResults: [
    { channel: 'CH1', reference: '1000.00Ω', measured: '999.95Ω', deviation: '+0.005%', result: '合格' },
    { channel: 'CH2', reference: '1000.00Ω', measured: '1000.03Ω', deviation: '-0.003%', result: '合格' },
    { channel: 'CH3', reference: '1000.00Ω', measured: '999.98Ω', deviation: '+0.002%', result: '合格' },
    { channel: 'CH4', reference: '1000.00Ω', measured: '1000.08Ω', deviation: '-0.008%', result: '合格' },
    { channel: 'CH5', reference: '1000.00Ω', measured: '999.92Ω', deviation: '+0.008%', result: '合格' },
    { channel: 'CH6', reference: '1000.00Ω', measured: '1000.05Ω', deviation: '-0.005%', result: '合格' },
  ],
}

function getStatusStyle(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 { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)', border: '1px solid #D9D9D9' }
  }
}

export default function CalibrationPage() {
  const [filterSN, setFilterSN] = useState('')
  const [filterStatus, setFilterStatus] = useState('全部')
  const [filterOperator, setFilterOperator] = useState('全部')
  const [currentPage, setCurrentPage] = useState(1)
  const [detailDrawer, setDetailDrawer] = useState<typeof calibrationData[0] | null>(null)
  const pageSize = 6

  const filtered = calibrationData.filter(r => {
    if (filterSN && !r.sn.toLowerCase().includes(filterSN.toLowerCase())) return false
    if (filterStatus !== '全部' && r.status !== filterStatus) return false
    if (filterOperator !== '全部' && r.operator !== filterOperator) return false
    return true
  })
  const totalPages = Math.ceil(filtered.length / pageSize)
  const paged = filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize)

  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>
        <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>
      </div>

      {/* Info Banner */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: 16, backgroundColor: '#F9F0FF', borderRadius: 8, marginBottom: 24, border: '1px solid #D3ADF7' }}>
        <Info size={18} style={{ color: '#722ED1', flexShrink: 0, marginTop: 2 }} />
        <div style={{ fontSize: 14, color: '#722ED1', lineHeight: 1.6 }}>
          校准管理仅针对采集板（ACB系列），其他类型板卡无需校准。校准到期前30天系统会自动提醒。
        </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 }}>采集板SN号</label>
            <input type="text" value={filterSN} onChange={e => { setFilterSN(e.target.value); setCurrentPage(1) }} placeholder="输入SN号搜索" style={{ width: '100%', padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
          </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={filterOperator} onChange={e => { setFilterOperator(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
              {operatorOptions.map(o => <option key={o} value={o}>{o}</option>)}
            </select>
          </div>
          <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, flexShrink: 0 }}>
            <Search size={14} />查询
          </button>
        </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 16px', textAlign: 'left', fontSize: 14, fontWeight: 600, color: 'rgba(0,0,0,0.85)', borderBottom: '1px solid #F0F0F0' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {paged.map(row => (
              <tr key={row.id} style={{ borderBottom: '1px solid #F0F0F0' }}>
                <td style={{ padding: '12px 16px', fontSize: 14, fontWeight: 500 }}>{row.sn}</td>
                <td style={{ padding: '12px 16px', fontSize: 14, color: 'rgba(0,0,0,0.65)' }}>{row.boardModel}</td>
                <td style={{ padding: '12px 16px', fontSize: 14, color: 'rgba(0,0,0,0.65)' }}>{row.calibDate}</td>
                <td style={{ padding: '12px 16px', fontSize: 14, color: 'rgba(0,0,0,0.65)' }}>{row.expiryDate}</td>
                <td style={{ padding: '12px 16px', fontSize: 14, color: 'rgba(0,0,0,0.65)' }}>{row.operator}</td>
                <td style={{ padding: '12px 16px' }}>
                  <span style={{ ...getStatusStyle(row.status), padding: '2px 8px', borderRadius: 4, fontSize: 12 }}>{row.status}</span>
                </td>
                <td style={{ padding: '12px 16px' }}>
                  <div style={{ display: 'flex', gap: 12 }}>
                    <button onClick={() => setDetailDrawer(row)} style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 14, display: 'flex', alignItems: 'center', gap: 4 }}>
                      <Eye size={14} />详情
                    </button>
                    <button style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 14, display: 'flex', alignItems: 'center', gap: 4 }}>
                      <FileDown size={14} />校准文件
                    </button>
                  </div>
                </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)' }}>显示 {(currentPage - 1) * pageSize + 1}-{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} style={{ padding: '4px 8px', border: '1px solid #D9D9D9', borderRadius: 4, backgroundColor: '#fff', cursor: currentPage === totalPages ? 'not-allowed' : 'pointer', opacity: currentPage === totalPages ? 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: 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 }}>校准详情 - {detailDrawer.sn}</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)' }}>采集板SN：</span>{detailDrawer.sn}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>板卡型号：</span>{detailDrawer.boardModel}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>通道数：</span>{detailDrawer.channel}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>综合偏差：</span>{detailDrawer.deviation}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>校准日期：</span>{detailDrawer.calibDate}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>到期日期：</span>{detailDrawer.expiryDate}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>校准人员：</span>{detailDrawer.operator}</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 }}>通道校准结果</h4>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead>
                    <tr>
                      {['通道', '参考值', '测量值', '偏差', '结果'].map(h => (
                        <th key={h} style={{ padding: '8px 10px', textAlign: 'left', fontSize: 12, fontWeight: 600, color: 'rgba(0,0,0,0.65)', borderBottom: '1px solid #F0F0F0' }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {calibDetailData.calibResults.map((r, i) => (
                      <tr key={i}>
                        <td style={{ padding: '8px 10px', fontSize: 13 }}>{r.channel}</td>
                        <td style={{ padding: '8px 10px', fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>{r.reference}</td>
                        <td style={{ padding: '8px 10px', fontSize: 13 }}>{r.measured}</td>
                        <td style={{ padding: '8px 10px', fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>{r.deviation}</td>
                        <td style={{ padding: '8px 10px' }}>
                          <span style={{ ...getStatusStyle(r.result), padding: '1px 6px', borderRadius: 4, fontSize: 11 }}>{r.result}</span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>
                <FileDown size={14} />下载校准文件
              </button>
              <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>
  )
}
