'use client'
import { useState } from 'react'
import Link from 'next/link'
import { Download, Search, X, Eye, CheckCircle, Clock, Package, Trash2, AlertTriangle, ChevronLeft, ChevronRight } from 'lucide-react'
import { useApi } from '@/lib/hooks'

interface ScrapRecord {
  id: number
  sn: string
  model: string
  reason: string
  applicant: string
  status: string
  order_id: string
  date: string
  value: number
  materials: string[]
}

const steps = [
  { label: '申请报废', desc: '维修工单发起' },
  { label: '主管审批', desc: '审核报废原因' },
  { label: '物料检测', desc: '检测可回收物料' },
  { label: '回收入库', desc: '物料回收登记' },
  { label: '报废完成', desc: '设备注销' },
]

const statusOptions = ['全部', '待审批', '审批中', '已审批', '已驳回', '回收中', '已回收']

function getStatusStyle(status: string) {
  switch (status) {
    case '待审批': return { backgroundColor: '#FFFBE6', color: '#FAAD14', border: '1px solid #FFE58F' }
    case '审批中': return { backgroundColor: '#eef5f0', color: '#4a7c59', border: '1px solid #a3c4ad' }
    case '已审批': return { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' }
    case '已驳回': return { backgroundColor: '#FFF1F0', color: '#FF4D4F', border: '1px solid #FFCCC7' }
    case '回收中': return { backgroundColor: '#eef5f0', color: '#4a7c59', border: '1px solid #a3c4ad' }
    case '已回收': return { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' }
    default: return { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)', border: '1px solid #D9D9D9' }
  }
}

export default function ScrapPage() {
  const { data: scrapRaw, loading } = useApi<ScrapRecord[]>('/api/scrap', [])

  // Map DB fields to display fields
  const scrapData = scrapRaw.map(r => ({
    id: r.id, sn: r.sn, model: r.model, reason: r.reason, applicant: r.applicant,
    status: r.status, orderId: r.order_id, date: r.date, value: r.value, materials: r.materials,
  }))

  // Dynamic stats
  const statsCards = [
    { label: '报废总数', value: scrapData.length, color: 'rgba(0,0,0,0.85)' },
    { label: '待审批', value: scrapData.filter(r => r.status === '待审批').length, color: '#FAAD14' },
    { label: '已审批待回收', value: scrapData.filter(r => r.status === '已审批').length, color: '#4a7c59' },
    { label: '已回收', value: scrapData.filter(r => r.status === '已回收').length, color: '#52C41A' },
  ]

  const [filterSN, setFilterSN] = useState('')
  const [filterStatus, setFilterStatus] = useState('全部')
  const [filterDate, setFilterDate] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [detailDrawer, setDetailDrawer] = useState<typeof scrapData[0] | null>(null)
  const [approvalDrawer, setApprovalDrawer] = useState<typeof scrapData[0] | null>(null)
  const [recoveryDrawer, setRecoveryDrawer] = useState<typeof scrapData[0] | null>(null)
  const [approvalNote, setApprovalNote] = useState('')
  const [recoveryNote, setRecoveryNote] = useState('')
  const [checkedMaterials, setCheckedMaterials] = useState<string[]>([])
  const pageSize = 5

  if (loading) return <div style={{ padding: 24 }}>加载中...</div>

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

  const openApproval = (item: typeof scrapData[0]) => { setApprovalDrawer(item); setApprovalNote('') }
  const openRecovery = (item: typeof scrapData[0]) => { setRecoveryDrawer(item); setRecoveryNote(''); setCheckedMaterials([]) }

  const toggleMaterial = (m: string) => {
    setCheckedMaterials(prev => prev.includes(m) ? prev.filter(x => x !== m) : [...prev, m])
  }

  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>

      {/* Steps */}
      <div style={{ backgroundColor: '#fff', borderRadius: 8, padding: '24px 32px', marginBottom: 24, boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
          {steps.map((step, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
                <div style={{ width: 32, height: 32, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 600, backgroundColor: '#eef5f0', color: '#4a7c59', marginBottom: 8 }}>{i + 1}</div>
                <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 2 }}>{step.label}</div>
                <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.45)' }}>{step.desc}</div>
              </div>
              {i < steps.length - 1 && (
                <div style={{ flex: 1, height: 1, backgroundColor: '#D9D9D9', margin: '16px 12px 0' }} />
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Stats Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {statsCards.map((card, i) => (
          <div key={i} style={{ backgroundColor: '#fff', borderRadius: 8, padding: '20px 24px', boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
            <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.45)', marginBottom: 8 }}>{card.label}</div>
            <div style={{ fontSize: 28, fontWeight: 600, color: card.color }}>{card.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 }}>设备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>
            <input type="date" value={filterDate} onChange={e => { setFilterDate(e.target.value); setCurrentPage(1) }} style={{ width: '100%', padding: '6px 12px', border: '1px solid #D9D9D9', borderRadius: 6, fontSize: 14, boxSizing: 'border-box' }} />
          </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.model}</td>
                <td style={{ padding: '12px 16px', fontSize: 14, color: 'rgba(0,0,0,0.65)', maxWidth: 180 }}>
                  <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.reason}</div>
                </td>
                <td style={{ padding: '12px 16px', fontSize: 14, color: 'rgba(0,0,0,0.65)' }}>{row.applicant}</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' }}>
                  <Link href={`/repair/${row.orderId}`} style={{ fontSize: 14, color: '#4a7c59', textDecoration: 'none' }}>{row.orderId}</Link>
                </td>
                <td style={{ padding: '12px 16px' }}>
                  <div style={{ display: 'flex', gap: 10 }}>
                    <button onClick={() => setDetailDrawer(row)} style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13 }}>详情</button>
                    {row.status === '待审批' && <button onClick={() => openApproval(row)} style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13 }}>审批</button>}
                    {row.status === '已审批' && <button onClick={() => openRecovery(row)} style={{ color: '#4a7c59', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13 }}>回收入库</button>}
                    {row.status === '已驳回' && <button style={{ color: '#FA8C16', cursor: 'pointer', border: 'none', background: 'none', fontSize: 13 }}>重新申请</button>}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <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} 条</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: 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 }}>设备信息</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.model}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>报废日期：</span>{detailDrawer.date}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>残值评估：</span>¥{detailDrawer.value.toLocaleString()}</div>
                  <div style={{ gridColumn: '1 / -1' }}><span style={{ color: 'rgba(0,0,0,0.45)' }}>报废原因：</span>{detailDrawer.reason}</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>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, fontSize: 13 }}>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>申请人：</span>{detailDrawer.applicant}</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><span style={{ color: 'rgba(0,0,0,0.45)' }}>来源工单：</span><Link href={`/repair/${detailDrawer.orderId}`} style={{ color: '#4a7c59', textDecoration: 'none' }}>{detailDrawer.orderId}</Link></div>
                </div>
              </div>
              {/* 可回收物料 */}
              {detailDrawer.materials.length > 0 && (
                <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: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {detailDrawer.materials.map((m, i) => (
                      <span key={i} style={{ padding: '4px 10px', borderRadius: 4, fontSize: 12, backgroundColor: '#eef5f0', color: '#4a7c59', border: '1px solid #a3c4ad' }}>{m}</span>
                    ))}
                  </div>
                </div>
              )}
              {/* 审批记录 */}
              <div style={{ padding: 16, backgroundColor: '#FAFAFA', borderRadius: 8, border: '1px solid #F0F0F0' }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>审批记录</h4>
                <div style={{ display: 'flex', gap: 12, paddingBottom: 12 }}>
                  <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: '#4a7c59', marginTop: 6, flexShrink: 0 }} />
                  <div style={{ fontSize: 13 }}>
                    <div style={{ fontWeight: 500, marginBottom: 4 }}>提交报废申请</div>
                    <div style={{ color: 'rgba(0,0,0,0.45)' }}>维修工单{detailDrawer.orderId}发起报废</div>
                    <div style={{ color: 'rgba(0,0,0,0.35)', marginTop: 4 }}>{detailDrawer.date} · {detailDrawer.applicant}</div>
                  </div>
                </div>
              </div>
            </div>
            <div style={{ padding: '16px 24px', borderTop: '1px solid #F0F0F0', display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button onClick={() => setDetailDrawer(null)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>关闭</button>
              {detailDrawer.status === '待审批' && (
                <button onClick={() => { setDetailDrawer(null); openApproval(detailDrawer) }} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>去审批</button>
              )}
              {detailDrawer.status === '已审批' && (
                <button onClick={() => { setDetailDrawer(null); openRecovery(detailDrawer) }} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>回收入库</button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Approval Drawer */}
      {approvalDrawer && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setApprovalDrawer(null)} 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={() => setApprovalDrawer(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={{ display: 'flex', alignItems: 'center', gap: 8, padding: 12, borderRadius: 8, marginBottom: 20, backgroundColor: '#FFF1F0', border: '1px solid #FFCCC7' }}>
                <AlertTriangle size={16} style={{ color: '#FF4D4F', flexShrink: 0 }} />
                <span style={{ fontSize: 13, color: '#FF4D4F' }}>报废操作不可逆，请谨慎审批</span>
              </div>
              <div style={{ padding: 16, backgroundColor: '#FAFAFA', borderRadius: 8, marginBottom: 20, border: '1px solid #F0F0F0' }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>报废设备摘要</h4>
                <div style={{ fontSize: 13, lineHeight: 2 }}>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>设备SN：</span>{approvalDrawer.sn}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>型号：</span>{approvalDrawer.model}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>报废原因：</span>{approvalDrawer.reason}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>残值评估：</span>¥{approvalDrawer.value.toLocaleString()}</div>
                  <div><span style={{ color: 'rgba(0,0,0,0.45)' }}>申请人：</span>{approvalDrawer.applicant}</div>
                </div>
              </div>
              {approvalDrawer.materials.length > 0 && (
                <div style={{ marginBottom: 20 }}>
                  <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 8 }}>可回收物料</h4>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {approvalDrawer.materials.map((m, i) => (
                      <span key={i} style={{ padding: '4px 10px', borderRadius: 4, fontSize: 12, backgroundColor: '#eef5f0', color: '#4a7c59', border: '1px solid #a3c4ad' }}>{m}</span>
                    ))}
                  </div>
                </div>
              )}
              <div>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>审批意见</label>
                <textarea value={approvalNote} onChange={e => setApprovalNote(e.target.value)} rows={4} 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={() => setApprovalDrawer(null)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <button onClick={() => setApprovalDrawer(null)} style={{ padding: '8px 20px', border: '1px solid #FFCCC7', borderRadius: 6, backgroundColor: '#fff', color: '#FF4D4F', cursor: 'pointer', fontSize: 14 }}>驳回</button>
              <button onClick={() => setApprovalDrawer(null)} style={{ padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14 }}>审批通过</button>
            </div>
          </div>
        </div>
      )}

      {/* Recovery Drawer */}
      {recoveryDrawer && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
          <div onClick={() => setRecoveryDrawer(null)} 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={() => setRecoveryDrawer(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: 20, border: '1px solid #F0F0F0' }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 8 }}>报废设备</h4>
                <div style={{ fontSize: 13, color: 'rgba(0,0,0,0.65)' }}>{recoveryDrawer.sn} · {recoveryDrawer.model}</div>
              </div>
              <div style={{ marginBottom: 20 }}>
                <h4 style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>物料检测与回收</h4>
                {recoveryDrawer.materials.map((m, i) => (
                  <label key={i} onClick={() => toggleMaterial(m)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 6, marginBottom: 8, cursor: 'pointer', border: '1px solid #F0F0F0', backgroundColor: checkedMaterials.includes(m) ? '#F6FFED' : '#fff' }}>
                    <div style={{ width: 18, height: 18, borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', border: checkedMaterials.includes(m) ? 'none' : '1px solid #D9D9D9', backgroundColor: checkedMaterials.includes(m) ? '#52C41A' : '#fff' }}>
                      {checkedMaterials.includes(m) && <CheckCircle size={12} color="#fff" />}
                    </div>
                    <span style={{ fontSize: 13, color: checkedMaterials.includes(m) ? '#52C41A' : 'rgba(0,0,0,0.65)' }}>{m}</span>
                    {checkedMaterials.includes(m) && <span style={{ fontSize: 11, color: '#52C41A', marginLeft: 'auto' }}>已检测</span>}
                  </label>
                ))}
              </div>
              <div>
                <label style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8 }}>回收备注</label>
                <textarea value={recoveryNote} onChange={e => setRecoveryNote(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={() => setRecoveryDrawer(null)} style={{ padding: '8px 20px', border: '1px solid #D9D9D9', borderRadius: 6, backgroundColor: '#fff', cursor: 'pointer', fontSize: 14 }}>取消</button>
              <Link href="/registration" onClick={() => setRecoveryDrawer(null)} style={{ display: 'inline-flex', alignItems: 'center', padding: '8px 20px', border: 'none', borderRadius: 6, backgroundColor: '#4a7c59', color: '#fff', cursor: 'pointer', fontSize: 14, textDecoration: 'none' }}>确认回收入库</Link>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}