'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Download, Plus, Search, Info, ChevronLeft, ChevronRight, X, Check } from 'lucide-react'

const allAuthItems = [
  { id: '1D_SP', name: '1D SP', description: '一维自然电位法' },
  { id: '2D_SP', name: '2D SP', description: '二维自然电位法' },
  { id: '3D_SP', name: '3D SP', description: '三维自然电位法' },
  { id: '1D_VES', name: '1D VES', description: '一维垂向电测深' },
  { id: '2D_ERT', name: '2D ERT', description: '二维电阻率成像' },
  { id: '3D_ERT', name: '3D ERT', description: '三维电阻率成像' },
  { id: '1D_IP', name: '1D IP', description: '一维激发极化法' },
  { id: '2D_IP', name: '2D IP', description: '二维激发极化法' },
  { id: '3D_IP', name: '3D IP', description: '三维激发极化法' },
  { id: 'CROSS', name: '跨孔', description: '跨孔电阻率成像' },
  { id: 'WATER', name: '水上', description: '水上电法探测' },
]

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

const mockLicenses = [
  { id: 1, model: 'GD-30', modules: '2D ERT, 3D ERT, 1D IP, 2D IP, 3D IP, 跨孔, 水上', expiry: '2025-12-31', date: '2025-01-15', status: '生效' },
  { id: 2, model: 'GD-20', modules: '2D ERT, 3D ERT, 1D IP, 2D IP', expiry: '2025-06-30', date: '2024-07-01', status: '生效' },
  { id: 3, model: 'GD-10', modules: '1D SP, 2D SP, 1D VES, 2D ERT', expiry: '2024-12-31', date: '2024-01-10', status: '已停用' },
  { id: 4, model: 'GD-30', modules: '全部模块', expiry: '2026-06-30', date: '2025-03-20', status: '生效' },
  { id: 5, model: 'GD-20', modules: '2D ERT, 1D IP, 2D IP', expiry: '2025-09-15', date: '2025-02-10', status: '生效' },
  { id: 6, model: 'GD-10', modules: '1D SP, 2D SP', expiry: '2024-06-30', date: '2023-07-01', status: '已停用' },
  { id: 7, model: 'GD-30', modules: '3D ERT, 3D IP, 跨孔', expiry: '2025-08-20', date: '2025-01-05', status: '生效' },
  { id: 8, model: 'GD-20', modules: '1D VES, 2D ERT, 1D IP', expiry: '2025-11-30', date: '2025-04-01', status: '草稿' },
]

const statusStyle = (status: string) => {
  switch (status) {
    case '生效': return { backgroundColor: '#F6FFED', color: '#52C41A', border: '1px solid #B7EB8F' }
    case '草稿': return { backgroundColor: '#FFFBE6', color: '#FAAD14', border: '1px solid #FFE58F' }
    case '已停用': return { backgroundColor: '#FAFAFA', color: 'rgba(0,0,0,0.45)', border: '1px solid #D9D9D9' }
    default: return {}
  }
}

export default function LicensesPage() {
  const router = useRouter()
  const [filterModel, setFilterModel] = useState('')
  const [filterStatus, setFilterStatus] = useState('')
  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

  const filtered = mockLicenses.filter(l => {
    if (filterModel && l.model !== filterModel) return false
    if (filterStatus && l.status !== filterStatus) return false
    return true
  })
  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>
          <h2 className="text-2xl font-semibold mb-1">授权管理</h2>
          <p className="text-sm" style={{ color: 'rgba(0,0,0,0.45)' }}>管理设备授权许可</p>
        </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={() => { setDrawerOpen(true); setDrawerModel(''); setSelectedItems([]); setDrawerExpiry('1year'); setDrawerCustomDate('') }} 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)' }}>
          授权管理用于控制设备可使用的功能模块。每台设备需要有效的授权才能使用对应的测量方法。授权到期前30天系统会自动提醒。
        </div>
      </div>

      <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)} className="px-3 py-1.5 rounded text-sm" style={{ border: '1px solid #D9D9D9', minWidth: 140 }}>
              <option value="">全部型号</option>
              <option value="GD-10">GD-10</option>
              <option value="GD-20">GD-20</option>
              <option value="GD-30">GD-30</option>
            </select>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm" style={{ color: 'rgba(0,0,0,0.65)' }}>状态</span>
            <select value={filterStatus} onChange={e => setFilterStatus(e.target.value)} className="px-3 py-1.5 rounded text-sm" style={{ border: '1px solid #D9D9D9', minWidth: 120 }}>
              <option value="">全部状态</option>
              <option value="生效">生效</option>
              <option value="草稿">草稿</option>
              <option value="已停用">已停用</option>
            </select>
          </div>
          <button onClick={() => setCurrentPage(1)} className="flex items-center gap-1 px-4 py-1.5 rounded text-sm text-white" style={{ backgroundColor: '#4a7c59' }}>
            <Search size={14} />查询
          </button>
        </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" style={{ borderBottom: '1px solid #F0F0F0' }}>{row.model}</td>
                <td className="px-4 py-3 text-sm" style={{ borderBottom: '1px solid #F0F0F0', maxWidth: 300 }}>
                  <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{row.modules}</div>
                </td>
                <td className="px-4 py-3 text-sm" style={{ borderBottom: '1px solid #F0F0F0' }}>{row.expiry}</td>
                <td className="px-4 py-3 text-sm" style={{ borderBottom: '1px solid #F0F0F0' }}>{row.date}</td>
                <td className="px-4 py-3 text-sm" style={{ borderBottom: '1px solid #F0F0F0' }}>
                  <span className="px-2 py-0.5 rounded text-xs" style={statusStyle(row.status)}>{row.status}</span>
                </td>
                <td className="px-4 py-3 text-sm" style={{ borderBottom: '1px solid #F0F0F0' }}>
                  <div className="flex items-center gap-3">
                    <button className="text-sm" style={{ color: '#4a7c59' }}>编辑</button>
                    <button className="text-sm" style={{ color: row.status === '已停用' ? 'rgba(0,0,0,0.25)' : '#FF4D4F' }} disabled={row.status === '已停用'}>停用</button>
                  </div>
                </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>
                <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>
                  <option value="GD-10">GD-10</option>
                  <option value="GD-20">GD-20</option>
                  <option value="GD-30">GD-30</option>
                </select>
              </div>
              <div className="mb-6">
                <label className="block text-sm mb-2" style={{ color: 'rgba(0,0,0,0.85)' }}>授权期限</label>
                <select value={drawerExpiry} onChange={e => setDrawerExpiry(e.target.value)} className="w-full px-3 py-2 rounded text-sm" style={{ border: '1px solid #D9D9D9' }}>
                  <option value="1year">1年</option>
                  <option value="2year">2年</option>
                  <option value="3year">3年</option>
                  <option value="permanent">永久</option>
                  <option value="custom">自定义</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>
                    </tr>
                  </thead>
                  <tbody>
                    {allAuthItems.map(item => (
                      <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' }}>{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>
              <button onClick={() => setDrawerOpen(false)} className="w-full py-2 rounded-lg text-sm text-white" style={{ backgroundColor: '#4a7c59' }}>保存</button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
