'use client'
import { useState, Suspense } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Download, Plus, Info, ChevronLeft, ChevronRight, X, Check, ArrowLeft } from 'lucide-react'
import { useApi } from '@/lib/hooks'

interface LicenseItem { id: number; model: string; modules: string; expiry: string; status: string }
interface DeviceModel { id: number; name: string; code: string; status: string }

const allAuthItems = [
  { id: '1D', name: '一维自电/电阻率/激电测试模块', description: '包含一维自然电位法、电阻率测深、激发极化测深', category: '一维' },
  { id: '2D', name: '二维自电/电阻率/激电测试模块', description: '包含二维自然电位法、电阻率成像、激发极化成像', category: '二维' },
  { id: '3D', name: '三维自电/电阻率/激电测试模块', description: '包含三维自然电位法、电阻率成像、激发极化成像', category: '三维' },
  { id: 'WATER', name: '水上', description: '水上电法探测', category: '水上' },
  { id: 'CROSS', name: '跨孔', description: '跨孔电阻率成像', category: '跨孔' },
  { id: 'CF', name: '电流场法', description: '电流场法', category: '电流场法' },
]

const authCategories = ['一维', '二维', '三维', '水上', '跨孔', '电流场法']

const modelPresets: Record<string, string[]> = {
  'GD-10': ['1D', '2D'],
  'GD-20': ['1D', '2D', '3D'],
  'GD-30': ['1D', '2D', '3D', 'WATER', 'CROSS', 'CF'],
}

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

function LicensesContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const modelParam = searchParams.get('model') || ''
  const { data: licensesData, loading, refetch } = useApi<LicenseItem[]>('/api/licenses', [])
  const { data: deviceModels } = useApi<DeviceModel[]>('/api/models', [])

  // 从型号管理跳转时，锁定到该型号
  const isFromModels = !!modelParam
  // 从型号名（如 "GD-30 Supreme"）提取短名（如 "GD-30"）
  const modelShortName = modelParam ? modelParam.replace(' Supreme', '') : ''

  const [filterModel, setFilterModel] = useState(modelShortName)
  const [currentPage, setCurrentPage] = useState(1)
  const [drawerOpen, setDrawerOpen] = useState(false)
  const [drawerModel, setDrawerModel] = useState('')
  const [drawerExpiry, setDrawerExpiry] = useState('1year')
  const [drawerCustomDate, setDrawerCustomDate] = useState('')
  const [selectedItems, setSelectedItems] = useState<string[]>([])
  const pageSize = 5

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

  const filtered = licensesData.filter(l => {
    if (filterModel && l.model !== filterModel) return false
    return true
  })
  // 从型号管理进来时，查找该型号已有的授权记录
  const existingLicense = isFromModels ? licensesData.find(l => l.model === modelShortName) : null
  const totalPages = Math.ceil(filtered.length / pageSize)
  const paged = filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize)

  const handleModelChange = (model: string) => {
    setDrawerModel(model)
    if (modelPresets[model]) {
      setSelectedItems([...modelPresets[model]])
    } else {
      setSelectedItems([])
    }
  }

  const toggleItem = (id: string) => {
    setSelectedItems(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }

  const selectAll = () => setSelectedItems(allAuthItems.map(i => i.id))
  const clearAll = () => setSelectedItems([])

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          {isFromModels && (
            <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 className="text-2xl font-semibold mb-1">{isFromModels ? `授权管理 — ${modelParam}` : '授权管理'}</h2>
            <p className="text-sm" style={{ color: 'rgba(0,0,0,0.45)' }}>管理设备授权许可</p>
          </div>
        </div>
        <div className="flex gap-3">
          <button className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm" style={{ border: '1px solid #D9D9D9', backgroundColor: '#fff', color: 'rgba(0,0,0,0.65)' }}>
            <Download size={16} />导出
          </button>
          <button onClick={() => {
            const preModel = isFromModels ? modelShortName : ''
            setDrawerOpen(true); setDrawerModel(preModel); setDrawerExpiry('1year'); setDrawerCustomDate('')
            if (preModel && modelPresets[preModel]) { setSelectedItems([...modelPresets[preModel]]) }
            else if (preModel && existingLicense) {
              // 已有授权记录时，回填已选项
              const existingModules = existingLicense.modules.split(', ')
              setSelectedItems(allAuthItems.filter(a => existingModules.includes(a.name)).map(a => a.id))
            } else { setSelectedItems([]) }
          }} className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm text-white" style={{ backgroundColor: '#4a7c59' }}>
            <Plus size={16} />选择授权项
          </button>
        </div>
      </div>

      <div className="flex items-start gap-3 p-4 rounded-lg mb-6" style={{ backgroundColor: '#E6FFFB', border: '1px solid #87E8DE' }}>
        <Info size={16} style={{ color: '#13C2C2', marginTop: 2, flexShrink: 0 }} />
        <div className="text-sm" style={{ color: 'rgba(0,0,0,0.65)' }}>
          每个设备型号对应一套授权模块配置。该授权模块定义了该型号设备可使用的全部测量方法，所有该型号设备共享同一套授权项。
        </div>
      </div>

      {!isFromModels && (
        <div className="bg-white rounded-lg p-4 mb-6" style={{ boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <span className="text-sm" style={{ color: 'rgba(0,0,0,0.65)' }}>设备型号</span>
              <select value={filterModel} onChange={e => { setFilterModel(e.target.value); setCurrentPage(1) }} className="px-3 py-1.5 rounded text-sm" style={{ border: '1px solid #D9D9D9', minWidth: 140 }}>
                <option value="">全部型号</option>
                {deviceModels.map(dm => (
                  <option key={dm.id} value={dm.name.replace(' Supreme', '')}>{dm.name}</option>
                ))}
              </select>
            </div>
          </div>
        </div>
      )}

      <div className="bg-white rounded-lg overflow-hidden" style={{ boxShadow: '0 1px 2px rgba(0,0,0,0.05)' }}>
        <table className="w-full">
          <thead>
            <tr style={{ backgroundColor: '#FAFAFA' }}>
              {['设备型号', '授权模块','操作'].map(h => (
                <th key={h} className="text-left px-4 py-3 text-sm font-medium" style={{ color: 'rgba(0,0,0,0.85)', borderBottom: '1px solid #F0F0F0' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {paged.map(row => (
              <tr key={row.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 text-sm font-medium" style={{ borderBottom: '1px solid #F0F0F0' }}>{row.model}</td>
                <td className="px-4 py-3 text-sm" style={{ borderBottom: '1px solid #F0F0F0', maxWidth: 400 }}>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                    {row.modules.split(', ').map(m => (
                      <span key={m} style={{ padding: '2px 8px', borderRadius: 4, fontSize: 11, backgroundColor: '#eef5f0', color: '#4a7c59', border: '1px solid #a3c4ad' }}>{m}</span>
                    ))}
                  </div>
                </td>
                <td className="px-4 py-3 text-sm" style={{ borderBottom: '1px solid #F0F0F0' }}>
                  <button className="text-sm" style={{ color: '#4a7c59', border: 'none', background: 'none', cursor: 'pointer' }}>编辑</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="flex items-center justify-between px-4 py-3" style={{ borderTop: '1px solid #F0F0F0' }}>
          <span className="text-sm" style={{ color: 'rgba(0,0,0,0.45)' }}>共 {filtered.length} 条</span>
          <div className="flex items-center gap-2">
            <button onClick={() => setCurrentPage(p => Math.max(1, p - 1))} disabled={currentPage === 1} className="p-1 rounded" style={{ border: '1px solid #D9D9D9', opacity: currentPage === 1 ? 0.4 : 1 }}><ChevronLeft size={16} /></button>
            {Array.from({ length: totalPages }, (_, i) => (
              <button key={i} onClick={() => setCurrentPage(i + 1)} className="w-8 h-8 rounded text-sm" style={{ 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' }}>{i + 1}</button>
            ))}
            <button onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))} disabled={currentPage === totalPages} className="p-1 rounded" style={{ border: '1px solid #D9D9D9', opacity: currentPage === totalPages ? 0.4 : 1 }}><ChevronRight size={16} /></button>
          </div>
        </div>
      </div>

      {drawerOpen && (
        <div className="fixed inset-0 z-50 flex">
          <div className="flex-1" style={{ backgroundColor: 'rgba(0,0,0,0.45)' }} onClick={() => setDrawerOpen(false)} />
          <div className="h-full overflow-y-auto" style={{ width: 640, backgroundColor: '#fff' }}>
            <div className="flex items-center justify-between px-6 py-4" style={{ borderBottom: '1px solid #F0F0F0' }}>
              <h3 className="text-lg font-semibold">选择授权项</h3>
              <button onClick={() => setDrawerOpen(false)}><X size={20} style={{ color: 'rgba(0,0,0,0.45)' }} /></button>
            </div>
            <div className="p-6">
              <div className="mb-6">
                <label className="block text-sm mb-2" style={{ color: 'rgba(0,0,0,0.85)' }}>设备型号</label>
                {isFromModels ? (
                  <div className="px-3 py-2 rounded text-sm" style={{ border: '1px solid #D9D9D9', backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.85)' }}>{modelParam}</div>
                ) : (
                  <select value={drawerModel} onChange={e => handleModelChange(e.target.value)} className="w-full px-3 py-2 rounded text-sm" style={{ border: '1px solid #D9D9D9' }}>
                    <option value="">请选择型号</option>
                    {deviceModels.map(dm => (
                      <option key={dm.id} value={dm.name.replace(' Supreme', '')}>{dm.name}</option>
                    ))}
                  </select>
                )}
              </div>
              {drawerExpiry === 'custom' && (
                <div className="mb-6">
                  <label className="block text-sm mb-2" style={{ color: 'rgba(0,0,0,0.85)' }}>自定义到期日期</label>
                  <input type="date" value={drawerCustomDate} onChange={e => setDrawerCustomDate(e.target.value)} className="w-full px-3 py-2 rounded text-sm" style={{ border: '1px solid #D9D9D9' }} />
                </div>
              )}
              <div className="mb-4">
                <div className="flex items-center justify-between mb-3">
                  <label className="text-sm font-medium" style={{ color: 'rgba(0,0,0,0.85)' }}>授权项目</label>
                  <div className="flex gap-3">
                    <button onClick={selectAll} className="text-sm" style={{ color: '#4a7c59' }}>全选</button>
                    <button onClick={clearAll} className="text-sm" style={{ color: 'rgba(0,0,0,0.45)' }}>清空</button>
                  </div>
                </div>
                <table className="w-full">
                  <thead>
                    <tr style={{ backgroundColor: '#FAFAFA' }}>
                      <th className="text-left px-3 py-2 text-sm font-medium" style={{ color: 'rgba(0,0,0,0.85)', borderBottom: '1px solid #F0F0F0', width: 50 }}>选择</th>
                      <th className="text-left px-3 py-2 text-sm font-medium" style={{ color: 'rgba(0,0,0,0.85)', borderBottom: '1px solid #F0F0F0' }}>分类</th>
                      <th className="text-left px-3 py-2 text-sm font-medium" style={{ color: 'rgba(0,0,0,0.85)', borderBottom: '1px solid #F0F0F0' }}>名称</th>
                      <th className="text-left px-3 py-2 text-sm font-medium" style={{ color: 'rgba(0,0,0,0.85)', borderBottom: '1px solid #F0F0F0' }}>说明</th>
                    </tr>
                  </thead>
                  <tbody>
                    {authCategories.map(cat => {
                      const items = allAuthItems.filter(i => i.category === cat)
                      return items.map((item, idx) => (
                        <tr key={item.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => toggleItem(item.id)}>
                          <td className="px-3 py-2" style={{ borderBottom: '1px solid #F0F0F0' }}>
                            <div className="w-4 h-4 rounded flex items-center justify-center" style={{ border: selectedItems.includes(item.id) ? 'none' : '1px solid #D9D9D9', backgroundColor: selectedItems.includes(item.id) ? '#4a7c59' : '#fff' }}>
                              {selectedItems.includes(item.id) && <Check size={12} color="#fff" />}
                            </div>
                          </td>
                          <td className="px-3 py-2 text-sm" style={{ borderBottom: '1px solid #F0F0F0', color: '#4a7c59', fontWeight: idx === 0 ? 500 : 400 }}>{idx === 0 ? cat : ''}</td>
                          <td className="px-3 py-2 text-sm" style={{ borderBottom: '1px solid #F0F0F0' }}>{item.name}</td>
                          <td className="px-3 py-2 text-sm" style={{ borderBottom: '1px solid #F0F0F0', color: 'rgba(0,0,0,0.45)' }}>{item.description}</td>
                        </tr>
                      ))
                    })}
                  </tbody>
                </table>
              </div>
              <div className="text-sm mb-6" style={{ color: 'rgba(0,0,0,0.45)' }}>已选择 {selectedItems.length} 项</div>
              <div className="flex items-start gap-2 p-3 rounded-lg mb-6" style={{ backgroundColor: '#eef5f0', border: '1px solid #a3c4ad' }}>
                <Info size={14} style={{ color: '#4a7c59', flexShrink: 0, marginTop: 2 }} />
                <span className="text-xs" style={{ color: '#4a7c59' }}>授权文件由选定的授权项与对应型号的配置文件共同生成，保存后系统将自动生成授权文件。</span>
              </div>
              <button onClick={async () => {
                if (!drawerModel) return
                const modules = selectedItems.map(id => allAuthItems.find(a => a.id === id)?.name).filter(Boolean).join(', ')
                await fetch('/api/licenses', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: drawerModel, modules, expiry: drawerExpiry === 'custom' ? drawerCustomDate : '', status: '生效' }) })
                refetch(); setDrawerOpen(false)
              }} className="w-full py-2 rounded-lg text-sm text-white" style={{ backgroundColor: '#4a7c59' }}>保存</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
