import { useState, useEffect } from 'react'
import { useNavigate, useLocation, Navigate } from 'react-router-dom'
import { listSkills } from '../services/api.js'
import EvaluationPanel from '../components/EvaluationPanel.jsx'
import { useAuth } from '../contexts/AuthContext.jsx'
import { useChatOverlay } from '../contexts/ChatOverlayContext.jsx'

const SUPER_ADMIN_EMAIL = '494161546@qq.com'
const SUPER_ADMIN_PHONE = '13136092523'

export default function SkillEvalPage({ overlayMode = false, overlaySkillId = null }) {
  const { user } = useAuth()
  const { openOverlay, closeOverlay } = useChatOverlay()
  const navigate = useNavigate()
  const location = useLocation()
  const isSuperAdmin = user?.email === SUPER_ADMIN_EMAIL || user?.phone === SUPER_ADMIN_PHONE
  const isAdmin = user?.role === 'admin' || isSuperAdmin
  const [skills, setSkills] = useState([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [selectedSkill, setSelectedSkill] = useState(null)

  useEffect(() => {
    if (!overlayMode && !isAdmin) {
      setLoading(false)
      return
    }
    setLoading(true)
    listSkills()
      .then(r => setSkills(r.list || []))
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [overlayMode, isAdmin])

  // 支持从上传页 / 浮层 / 其它入口携带 Skill ID，加载后自动选中进入评测
  useEffect(() => {
    if (loading) return
    const autoId = overlaySkillId || location.state?.autoEvalSkillId
    if (!autoId) return
    const found = skills.find(s => s.id === autoId)
    if (found) {
      setSelectedSkill(found)
      // 清除 state，避免刷新重复触发
      if (!overlaySkillId) window.history.replaceState({}, '')
    }
  }, [loading, skills, location.state, overlaySkillId])

  const filtered = skills.filter(s =>
    !search || (s.name || '').toLowerCase().includes(search.toLowerCase())
  )

  function handleAdopted(blob, zipName) {
    const file = new File([blob], zipName, { type: 'application/zip' })
    if (overlayMode) closeOverlay()
    navigate('/upload', { state: { preloadedFile: file } })
  }

  if (!overlayMode && !isAdmin) return <Navigate to="/" replace />

  if (selectedSkill) {
    return (
      <EvaluationPanel
        skill={selectedSkill}
        onClose={() => setSelectedSkill(null)}
        onAdopted={handleAdopted}
      />
    )
  }

  return (
    <div className="max-w-3xl mx-auto px-6 py-8">
      <div className="mb-6">
        <h1 className="text-[20px] font-semibold text-gray-900 mb-1">Skill 评测</h1>
        <p className="text-[13px] text-gray-500">选择一个 Skill 进行 AI 评测，评测完成后可直接采纳并重新发布</p>
      </div>

      <div className="mb-4">
        <input
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="搜索 Skill…"
          className="w-full px-3 py-2 text-[13px] border border-gray-200 rounded-lg focus:outline-none focus:border-brand-400"
        />
      </div>

      {loading ? (
        <div className="text-center py-16 text-[13px] text-gray-400">加载中…</div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-16 text-[13px] text-gray-400">
          {search ? '没有找到匹配的 Skill' : '暂无 Skill，请先上传'}
        </div>
      ) : (
        <div className="space-y-2">
          {filtered.map(s => (
            <div
              key={s.id}
              className="flex items-center gap-3 p-4 rounded-lg border border-gray-200 hover:border-brand-300 hover:bg-brand-50/30 transition-colors"
            >
              <div className="flex-1 min-w-0">
                <div className="text-[14px] font-medium text-gray-900 truncate">{s.name}</div>
                <div className="text-[12px] text-gray-500 truncate mt-0.5">
                  {s.desc || s.description || '无描述'}
                </div>
              </div>
              <div className="flex items-center gap-2 flex-shrink-0">
                {s.package_key && (
                  <button
                    onClick={() => openOverlay('sandbox', { skillId: s.id })}
                    className="px-3 py-1.5 text-[12px] rounded-md text-gray-600 border border-gray-200 hover:bg-gray-50"
                  >
                    ▶ 运行
                  </button>
                )}
                <button
                  onClick={() => setSelectedSkill(s)}
                  className="px-3 py-1.5 text-[12px] rounded-md text-white bg-brand-600 hover:bg-brand-700"
                >
                  去评测
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
