'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft, Upload, Download, Trash2, Edit, CheckCircle, Camera, X, AlertTriangle, Info } from 'lucide-react'

const modelMatchInfo: Record<string, { license: string; config: string; firmware: string }> = {
  'GD-30 Supreme': { license: 'LIC-GD30-全模块授权', config: 'CFG-GD30-v1.3.0', firmware: 'v2.3.5' },
  'GD-20 Supreme': { license: 'LIC-GD20-标准授权', config: 'CFG-GD20-v1.1.0', firmware: 'v1.8.5' },
  'GD-10 Supreme': { license: 'LIC-GD10-基础授权', config: 'CFG-GD10-v1.0.0', firmware: 'v1.5.2' },
}

const defaultBOM = [
  { id: 1, code: 'MB-2024-001', name: '主协板', sn: 'MCB-2024-0089', model: 'MCB-3000', calibration: '无需校准', qty: 1 },
  { id: 2, code: 'AC-2024-001', name: '采集板', sn: 'ACB-2024-0156', model: 'ACB-6000', calibration: '已校准', qty: 1 },
  { id: 3, code: 'AC-2024-002', name: '采集板', sn: 'ACB-2024-0157', model: 'ACB-6000', calibration: '已校准', qty: 1 },
  { id: 5, code: 'TX-2024-001', name: '发射板', sn: 'TXB-2024-0034', model: 'TXB-1000', calibration: '无需校准', qty: 1 },
  { id: 6, code: 'BS-2024-001', name: '升压板', sn: 'BST-2024-0021', model: 'BST-500', calibration: '无需校准', qty: 1 },
  { id: 7, code: 'CS-2024-001', name: '外壳机箱', sn: '-', model: 'GD30-CASE-A', calibration: '无需校准', qty: 1 },
]

const defaultChecklist = [
  { id: 1, name: '主板SN扫码绑定', required: true },
  { id: 2, name: '采集板SN录入（×6）', required: true },
  { id: 3, name: '发射板安装检查', required: true },
  { id: 4, name: '升压板安装检查', required: true },
  { id: 5, name: '线缆连接检查', required: true },
  { id: 6, name: '整机通电测试', required: true },
  { id: 7, name: 'GPS/北斗模块检测', required: true },
  { id: 8, name: 'WiFi通信测试', required: true },
  { id: 9, name: '蓝牙通信测试', required: true },
  { id: 10, name: '采集通道校准验证', required: true },
  { id: 11, name: '发射电压测试', required: true },
  { id: 12, name: '电池安装与充电测试', required: true },
  { id: 13, name: 'IP66防护检测', required: true },
  { id: 14, name: '固件版本校验', required: true },
  { id: 15, name: '配置文件写入', required: true },
  { id: 16, name: '授权文件写入', required: true },
  { id: 17, name: '整机功能测试', required: true },
  { id: 18, name: '数据采集验证', required: true },
  { id: 19, name: '外观检查', required: false },
  { id: 20, name: '标签粘贴', required: false },
  { id: 21, name: '配件清点', required: false },
  { id: 22, name: '包装检查', required: false },
]

export default function RegistrationPage() {
  const router = useRouter()
  const [deviceModel, setDeviceModel] = useState('GD-30 Supreme')
  const [hostSN, setHostSN] = useState('')
  const [boardSN, setBoardSN] = useState('')
  const [testStatus, setTestStatus] = useState('测试通过')
  const [productionDate, setProductionDate] = useState('')
  const [bomList, setBomList] = useState(defaultBOM)
  const [checkedItems, setCheckedItems] = useState<number[]>([])
  const [photoCount, setPhotoCount] = useState<Record<number, number>>({})
  const [importOpen, setImportOpen] = useState(false)
  const [photoOpen, setPhotoOpen] = useState<number | null>(null)
  const [photoNote, setPhotoNote] = useState('')

  const matchInfo = modelMatchInfo[deviceModel]
  const completedCount = checkedItems.length
  const totalCount = defaultChecklist.length

  const toggleCheck = (id: number) => {
    setCheckedItems(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }

  const removeBomItem = (id: number) => {
    setBomList(prev => prev.filter(b => b.id !== id))
  }

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, padding: 24, paddingBottom: 80 }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
          <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 }}>设备登记</h2>
            <p style={{ fontSize: 14, color: 'rgba(0,0,0,0.45)', margin: '4px 0 0' }}>登记新设备信息，填写装机信息与BOM清单</p>
          </div>
        </div>

        {/* 装机信息 */}
        <div style={{ backgroundColor: '#fff', borderRadius: 8, padding: 24, marginBottom: 24, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
          <h3 style={{ fontSize: 16, fontWeight: 600, margin: '0 0 20px' }}>装机信息</h3>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
            <div>
              <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}><span style={{ color: '#FF4D4F' }}>*</span> 设备型号</label>
              <select value={deviceModel} onChange={e => setDeviceModel(e.target.value)} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                <option value="GD-30 Supreme">GD-30 Supreme</option>
                <option value="GD-20 Supreme">GD-20 Supreme</option>
                <option value="GD-10 Supreme">GD-10 Supreme</option>
              </select>
            </div>
            <div>
              <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}><span style={{ color: '#FF4D4F' }}>*</span> 主机SN号</label>
              <input value={hostSN} onChange={e => setHostSN(e.target.value)} placeholder="如 GD30-20240308-001" 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> 主板SN号</label>
              <input value={boardSN} onChange={e => setBoardSN(e.target.value)} placeholder="如 MB20240308001" 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={testStatus} onChange={e => setTestStatus(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 }}>生产日期</label>
              <input type="date" value={productionDate} onChange={e => setProductionDate(e.target.value)} 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>
              <input value="张工" readOnly style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box', backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)' }} />
            </div>
          </div>
        </div>

        {/* 型号匹配提示 */}
        {matchInfo ? (
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: 16, backgroundColor: '#F6FFED', borderRadius: 8, marginBottom: 24, border: '1px solid #B7EB8F' }}>
            <CheckCircle size={18} style={{ color: '#52C41A', flexShrink: 0, marginTop: 2 }} />
            <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)', lineHeight: 1.8 }}>
              <div>已匹配型号 <span style={{ fontWeight: 600 }}>{deviceModel}</span> 的关联信息：</div>
              <div>授权文件：<span style={{ color: '#4a7c59' }}>{matchInfo.license}</span> · 配置文件：<span style={{ color: '#4a7c59' }}>{matchInfo.config}</span></div>
            </div>
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: 16, backgroundColor: '#FFFBE6', borderRadius: 8, marginBottom: 24, border: '1px solid #FFE58F' }}>
            <AlertTriangle size={18} style={{ color: '#FAAD14', flexShrink: 0, marginTop: 2 }} />
            <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>
              未匹配到型号关联信息，请先在<span style={{ color: '#4a7c59', cursor: 'pointer' }} onClick={() => router.push('/models')}>型号管理</span>中配置。
            </div>
          </div>
        )}

        {/* BOM 清单 */}
        <div style={{ backgroundColor: '#fff', borderRadius: 8, marginBottom: 24, 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 }}>装机清单 BOM</h3>
            <button onClick={() => setImportOpen(true)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 14px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 13 }}>
              <Upload size={14} />导入
            </button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ backgroundColor: '#FAFAFA' }}>
                {['物料编码', '物料名称', 'SN号', '型号', '校准状态', '数量', '操作'].map(h => (
                  <th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: 13, fontWeight: 600, color: 'rgba(0,0,0,0.85)', borderBottom: '1px solid #F0F0F0' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {bomList.map(item => (
                <tr key={item.id} style={{ borderBottom: '1px solid #F0F0F0' }}>
                  <td style={{ padding: '10px 16px', fontSize: 13 }}>{item.code}</td>
                  <td style={{ padding: '10px 16px', fontSize: 13 }}>{item.name}</td>
                  <td style={{ padding: '10px 16px', fontSize: 13, fontWeight: 500 }}>{item.sn}</td>
                  <td style={{ padding: '10px 16px', fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>{item.model}</td>
                  <td style={{ padding: '10px 16px' }}>
                    <span style={{ padding: '1px 6px', borderRadius: 4, fontSize: 11, ...(item.calibration === '已校准' ? { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' } : { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)', border: '1px solid #D9D9D9' }) }}>{item.calibration}</span>
                  </td>
                  <td style={{ padding: '10px 16px', fontSize: 13 }}>{item.qty}</td>
                  <td style={{ padding: '10px 16px' }}>
                    <div style={{ display: 'flex', gap: 8 }}>
                      <button style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13 }}><Edit size={13} /></button>
                      <button onClick={() => removeBomItem(item.id)} style={{ color: '#FF4D4F', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13 }}><Trash2 size={13} /></button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 装配 Checklist */}
        <div style={{ backgroundColor: '#fff', borderRadius: 8, padding: 24, marginBottom: 24, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
            <h3 style={{ fontSize: 16, fontWeight: 600, margin: 0 }}>装配 Checklist</h3>
            <span style={{ fontSize: 14, color: 'rgba(0,0,0,0.45)' }}>完成 <span style={{ color: '#4a7c59', fontWeight: 600 }}>{completedCount}</span>/{totalCount}</span>
          </div>
          {/* Progress bar */}
          <div style={{ height: 6, backgroundColor: '#F0F0F0', borderRadius: 3, marginBottom: 20, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${(completedCount / totalCount) * 100}%`, backgroundColor: '#4a7c59', borderRadius: 3, transition: 'width 0.3s' }} />
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {defaultChecklist.map((item, i) => {
              const isChecked = checkedItems.includes(item.id)
              const photos = photoCount[item.id] || 0
              return (
                <div key={item.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', borderRadius: 8, backgroundColor: isChecked ? '#F6FFED' : '#FAFAFA', border: isChecked ? '1px solid #B7EB8F' : '1px solid #F0F0F0', transition: 'all 0.2s' }}>
                  <div onClick={() => toggleCheck(item.id)} style={{ width: 20, height: 20, borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', border: isChecked ? 'none' : '2px solid #D9D9D9', backgroundColor: isChecked ? '#52C41A' : '#fff', flexShrink: 0 }}>
                    {isChecked && <CheckCircle size={14} color="#fff" />}
                  </div>
                  <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 600, backgroundColor: isChecked ? '#eef5f0' : '#F0F0F0', color: isChecked ? '#4a7c59' : 'rgba(0,0,0,0.45)', flexShrink: 0 }}>{i + 1}</div>
                  <div style={{ flex: 1 }}>
                    <span style={{ fontSize: 14, color: isChecked ? '#4a7c59' : 'rgba(0,0,0,0.85)' }}>{item.name}</span>
                    
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
                    {photos > 0 && <span style={{ fontSize: 12, color: '#52C41A' }}>{photos}张照片</span>}
                    <button onClick={() => { setPhotoOpen(item.id); setPhotoNote('') }} style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '4px 10px', border: '1px solid #D9D9D9', borderRadius: 4, backgroundColor: '#fff', cursor: 'pointer', fontSize: 12, color: 'rgba(0,0,0,0.65)' }}>
                      <Camera size={12} />{photos > 0 ? '管理' : '拍照'}
                    </button>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      </div>

      {/* Sticky Bottom Bar */}
      <div style={{ position: 'sticky', bottom: 0, backgroundColor: '#fff', borderTop: '1px solid #F0F0F0', padding: '12px 24px', display: 'flex', justifyContent: 'flex-end', gap: 12, zIndex: 10 }}>
        <button onClick={() => router.back()} style={{ padding: '8px 24px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
        <button style={{ padding: '8px 24px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>更新</button>
        <button style={{ padding: '8px 24px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>提交</button>
      </div>

      {/* Import BOM Dialog */}
      {importOpen && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div onClick={() => setImportOpen(false)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'relative', width: 520, 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 }}>导入BOM清单</h3>
              <button onClick={() => setImportOpen(false)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ padding: 24 }}>
              <div style={{ marginBottom: 20 }}>
                <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 8 }}>第一步：下载导入模板</div>
                <button style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 13 }}>
                  <Download size={14} />BOM导入模板.xlsx
                </button>
              </div>
              <div style={{ marginBottom: 20 }}>
                <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 8 }}>第二步：上传Excel文件</div>
                <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)' }}>点击或拖拽上传文件</div>
                  <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.25)', marginTop: 4 }}>支持 .xlsx / .xls / .csv 格式</div>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: 12, backgroundColor: '#FFFBE6', borderRadius: 6, border: '1px solid #FFE58F' }}>
                <Info size={14} style={{ color: '#FAAD14', flexShrink: 0, marginTop: 2 }} />
                <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.65)' }}>请确保文件格式与模板一致，物料编码和SN号为必填项。</span>
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setImportOpen(false)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={() => setImportOpen(false)} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>确认导入</button>
            </div>
          </div>
        </div>
      )}

      {/* Photo Upload Dialog */}
      {photoOpen !== null && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div onClick={() => setPhotoOpen(null)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'relative', width: 520, 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={() => setPhotoOpen(null)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ padding: 24 }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 20 }}>
                {Array.from({ length: photoCount[photoOpen] || 0 }).map((_, i) => (
                  <div key={i} style={{ position: 'relative', aspectRatio: '1', backgroundColor: '#F0F0F0', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Camera size={20} style={{ color: 'rgba(0,0,0,0.25)' }} />
                    <button onClick={() => setPhotoCount(prev => ({ ...prev, [photoOpen]: Math.max(0, (prev[photoOpen] || 0) - 1) }))} style={{ position: 'absolute', top: -6, right: -6, width: 18, height: 18, borderRadius: '50%', border: 'none', backgroundColor: '#FF4D4F', color: '#fff', fontSize: 10, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
                  </div>
                ))}
                <div onClick={() => setPhotoCount(prev => ({ ...prev, [photoOpen]: (prev[photoOpen] || 0) + 1 }))} style={{ aspectRatio: '1', border: '2px dashed #D9D9D9', borderRadius: 6, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', gap: 4 }}>
                  <Camera size={20} style={{ color: 'rgba(0,0,0,0.25)' }} />
                  <span style={{ fontSize: 11, color: 'rgba(0,0,0,0.35)' }}>添加</span>
                </div>
              </div>
              <div>
                <label style={{ display: 'block', fontSize: 13, fontWeight: 500, marginBottom: 6 }}>装配记录信息</label>
                <textarea value={photoNote} onChange={e => setPhotoNote(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={() => setPhotoOpen(null)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={() => setPhotoOpen(null)} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>确认上传（{photoCount[photoOpen] || 0}张）</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
