'use client'
import { useState, Suspense, useEffect, useCallback } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { ArrowLeft, Plus, Trash2, X, Info, CheckCircle } from 'lucide-react'
import { useApi } from '@/lib/hooks'

interface CategoryItem { id: number; name: string; status: string }

interface BomItem {
  id: number
  name: string
  material_name: string
  model: string
  versions: string[]
  qty: number
  required: boolean | number
  need_calibration: boolean | number
  enforce_version_match: boolean | number
  model_code: string
}

const modelNames: Record<string, string> = { GD30: 'GD-30 Supreme', GD20: 'GD-20 Supreme', GD10: 'GD-10 Supreme', GM10: 'GM-10 大地电磁仪', GT10: 'GT-10 瞬变电磁仪', GP10: 'GP-10 磁力仪' }

export default function BomPage() {
  return (
    <Suspense fallback={<div style={{ padding: 24 }}>加载中...</div>}>
      <BomContent />
    </Suspense>
  )
}

function BomContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const modelCode = searchParams.get('model') || 'GD30'
  const modelName = modelNames[modelCode] || modelCode
  const { data: categoriesData } = useApi<CategoryItem[]>('/api/material-categories', [])

  const [bomList, setBomList] = useState<BomItem[]>([])
  const [addDrawer, setAddDrawer] = useState(false)
  const [addForm, setAddForm] = useState({ name: '', materialName: '', model: '', versions: '', qty: 1, required: true, needCalibration: false, enforceVersionMatch: false })

  const fetchBom = useCallback(() => {
    fetch(`/api/models/bom?model=${modelCode}`).then(r => r.json()).then(d => setBomList(d))
  }, [modelCode])

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

  const removeBomItem = async (id: number) => {
    await fetch(`/api/models/bom?id=${id}`, { method: 'DELETE' })
    fetchBom()
  }

  const handleAdd = async () => {
    await fetch('/api/models/bom', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model_code: modelCode, name: addForm.name, material_name: addForm.materialName, model: addForm.model,
        versions: addForm.versions.split(',').map(v => v.trim()).filter(Boolean),
        qty: addForm.qty, required: addForm.required, need_calibration: addForm.needCalibration, enforce_version_match: addForm.enforceVersionMatch,
      })
    })
    fetchBom()
    setAddDrawer(false)
    setAddForm({ name: '', materialName: '', model: '', versions: '', qty: 1, required: true, needCalibration: false, enforceVersionMatch: false })
  }

  // 是否有多块采集板需要版本一致
  const hasMultiAcqBoards = bomList.some(b => b.name === '采集板' && b.qty >= 2 && b.enforce_version_match)

  return (
    <div style={{ padding: 24 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
        <button onClick={() => router.push('/models')} 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 }}>BOM表 — {modelName}</h2>
          <p style={{ fontSize: 14, color: 'rgba(0,0,0,0.45)', margin: '4px 0 0' }}>管理 {modelName} 型号的物料清单，定义装配所需板卡及版本</p>
        </div>
      </div>

      {/* Info Banner */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: 16, backgroundColor: '#eef5f0', borderRadius: 8, marginBottom: 24, border: '1px solid #a3c4ad' }}>
        <Info size={18} style={{ color: '#4a7c59', flexShrink: 0, marginTop: 2 }} />
        <div style={{ fontSize: 14, color: '#4a7c59', lineHeight: 1.6 }}>
          BOM表定义了该型号设备装配所需的全部物料。每种板卡可配置多个兼容版本，设备登记时按此清单进行装配。
        </div>
      </div>

      {/* 采集板版本一致性约束提示（仅当有多块采集板时显示） */}
      {hasMultiAcqBoards && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '12px 16px', backgroundColor: '#eef5f0', borderRadius: 8, marginBottom: 24, border: '1px solid #a3c4ad' }}>
          <CheckCircle size={16} style={{ color: '#4a7c59', flexShrink: 0 }} />
          <span style={{ fontSize: 13, color: '#4a7c59' }}>
            该型号包含 {bomList.find(b => b.name === '采集板' && b.qty >= 2)?.qty} 块采集板，已启用版本一致性约束：装配时所有采集板必须使用相同版本。
          </span>
        </div>
      )}

      {/* BOM Table */}
      <div style={{ backgroundColor: '#fff', borderRadius: 8, 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 }}>物料清单（共 {bomList.reduce((s, b) => s + b.qty, 0)} 件）</h3>
          <button onClick={() => setAddDrawer(true)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 16px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>
            <Plus size={16} />添加物料
          </button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ backgroundColor: '#FAFAFA' }}>
              {['物料名称', '物料分类', '物料类型', '兼容版本', '数量', '必需', '版本约束', '需校准', '操作'].map(h => (
                <th key={h} style={{ padding: '12px 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: '12px 16px', fontSize: 14, fontWeight: 500 }}>{item.material_name || item.name}</td>
                <td style={{ padding: '12px 16px', fontSize: 14, color: 'rgba(0,0,0,0.65)' }}>{item.name}</td>
                <td style={{ padding: '12px 16px', fontSize: 14, color: 'rgba(0,0,0,0.65)' }}>{item.model}</td>
                <td style={{ padding: '12px 16px' }}>
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    {item.versions.map(v => (
                      <span key={v} style={{ padding: '2px 8px', borderRadius: 4, fontSize: 12, backgroundColor: v === '-' ? '#FAFAFA' : '#F0F5FF', color: v === '-' ? 'rgba(0,0,0,0.25)' : '#597EF7', border: v === '-' ? '1px solid #D9D9D9' : '1px solid #ADC6FF' }}>{v}</span>
                    ))}
                  </div>
                </td>
                <td style={{ padding: '12px 16px', fontSize: 14 }}>{item.qty}</td>
                <td style={{ padding: '12px 16px' }}>
                  {item.required ? <span style={{ fontSize: 12, color: '#FF4D4F' }}>必需</span> : <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.25)' }}>可选</span>}
                </td>
                <td style={{ padding: '12px 16px' }}>
                  {item.qty >= 2 && item.enforce_version_match ? (
                    <span style={{ padding: '2px 8px', borderRadius: 4, fontSize: 11, backgroundColor: '#F0F5FF', color: '#597EF7', border: '1px solid #ADC6FF' }}>版本须一致</span>
                  ) : (
                    <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.25)' }}>-</span>
                  )}
                </td>
                <td style={{ padding: '12px 16px' }}>
                  {item.need_calibration ? <span style={{ padding: '2px 8px', borderRadius: 4, fontSize: 11, backgroundColor: '#FFFBE6', color: '#FAAD14', border: '1px solid #FFE58F' }}>需校准</span> : <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.25)' }}>-</span>}
                </td>
                <td style={{ padding: '12px 16px' }}>
                  <button onClick={() => removeBomItem(item.id)} style={{ color: '#FF4D4F', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <Trash2 size={13} />移除
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Add Drawer */}
      {addDrawer && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setAddDrawer(false)} style={{ position: 'absolute', inset: 0, backgroundColor: 'rgba(0,0,0,0.45)' }} />
          <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 480, 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={() => setAddDrawer(false)} style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 4 }}><X size={20} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 物料分类</label>
                <select value={addForm.name} onChange={e => setAddForm({ ...addForm, name: e.target.value })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14 }}>
                  <option value="">请选择</option>
                  {categoriesData.filter(c => c.status === '启用').map(c => <option key={c.name} value={c.name}>{c.name}</option>)}
                </select>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 物料名称</label>
                <input value={addForm.materialName} onChange={e => setAddForm({ ...addForm, materialName: e.target.value })} placeholder="如 GD30 主协板" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}><span style={{ color: '#FF4D4F' }}>*</span> 物料类型</label>
                <input value={addForm.model} onChange={e => setAddForm({ ...addForm, model: e.target.value })} placeholder="如 MCB-3000" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>兼容版本（逗号分隔）</label>
                <input value={addForm.versions} onChange={e => setAddForm({ ...addForm, versions: e.target.value })} placeholder="如 MB-V2.1, MB-V1.8" style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
                <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)', marginTop: 4 }}>支持多个版本，用逗号分隔</div>
              </div>
              <div style={{ marginBottom: 20 }}>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>数量</label>
                <input type="number" min={1} value={addForm.qty} onChange={e => setAddForm({ ...addForm, qty: parseInt(e.target.value) || 1 })} style={{ width: '100%', padding: '8px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
              </div>
              <div style={{ display: 'flex', gap: 24, marginBottom: 20 }}>
                <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 14, cursor: 'pointer' }}>
                  <input type="checkbox" checked={addForm.required} onChange={e => setAddForm({ ...addForm, required: e.target.checked })} />必需物料
                </label>
                <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 14, cursor: 'pointer' }}>
                  <input type="checkbox" checked={addForm.needCalibration} onChange={e => setAddForm({ ...addForm, needCalibration: e.target.checked })} />需要校准
                </label>
                {addForm.qty >= 2 && (
                  <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 14, cursor: 'pointer' }}>
                    <input type="checkbox" checked={addForm.enforceVersionMatch} onChange={e => setAddForm({ ...addForm, enforceVersionMatch: e.target.checked })} />版本须一致
                  </label>
                )}
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setAddDrawer(false)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={handleAdd} disabled={!addForm.name || !addForm.model} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: addForm.name && addForm.model ? '#4a7c59' : '#D9D9D9', color: '#fff', cursor: addForm.name && addForm.model ? 'pointer' : 'not-allowed', fontSize: 14 }}>添加</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
