import { useEffect, useMemo, useState } from 'react'
import { Navigate } from 'react-router-dom'
import { Activity, BarChart3, CheckCircle2, Download, Play, RefreshCcw, Trophy, Zap } from 'lucide-react'
import StatusBadge from '../components/StatusBadge.jsx'
import { useAuth } from '../contexts/AuthContext.jsx'
import { useChatOverlay } from '../contexts/ChatOverlayContext.jsx'
import { getOpsRankings } from '../services/api.js'
import { isAdminUser } from '../productConfig.js'

function fmtNum(value) {
  const n = Number(value ?? 0)
  if (!Number.isFinite(n)) return '0'
  return n.toLocaleString('zh-CN')
}

function fmtRate(value) {
  const n = Number(value ?? 0)
  if (!Number.isFinite(n)) return '—'
  return `${n.toFixed(n % 1 ? 1 : 0)}%`
}

function Metric({ icon: Icon, label, value, tone = 'gray' }) {
  const tones = {
    gray: 'bg-gray-100 text-gray-700',
    green: 'bg-emerald-50 text-emerald-700',
    blue: 'bg-blue-50 text-blue-700',
    amber: 'bg-amber-50 text-amber-700',
    rose: 'bg-rose-50 text-rose-700',
  }
  return (
    <div className="rounded-lg border border-gray-200 bg-white px-4 py-3">
      <div className="flex items-center gap-2 text-[12px] text-gray-500">
        <span className={`grid h-7 w-7 place-items-center rounded-md ${tones[tone] || tones.gray}`}>
          <Icon size={15} />
        </span>
        <span>{label}</span>
      </div>
      <div className="mt-2 text-[20px] font-semibold tabular-nums text-gray-900">{value}</div>
    </div>
  )
}

function EmptyState({ error, onRetry }) {
  return (
    <div className="flex min-h-[360px] flex-col items-center justify-center rounded-lg border border-dashed border-gray-300 bg-white px-6 text-center">
      <div className="text-[15px] font-medium text-gray-800">{error ? '运营数据加载失败' : '暂无运营数据'}</div>
      <div className="mt-2 max-w-md text-[13px] leading-6 text-gray-500">
        {error || '上传、发布、下载或 API 调用发生后，这里会自动形成领域与 SKU 排行。'}
      </div>
      {error && (
        <button
          type="button"
          onClick={onRetry}
          className="mt-4 inline-flex h-8 items-center gap-1.5 rounded-md border border-gray-200 bg-white px-3 text-[12px] font-medium text-gray-700 hover:bg-gray-50"
        >
          <RefreshCcw size={14} />
          重试
        </button>
      )}
    </div>
  )
}

export default function SkillOps() {
  const { user } = useAuth()
  const { openOverlay } = useChatOverlay()
  const isAdmin = isAdminUser(user)
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  async function load() {
    setLoading(true)
    setError('')
    try {
      setData(await getOpsRankings({ limit: 30 }))
    } catch (e) {
      setError(e?.friendlyMessage || e?.message || '请检查后端 /api/ops/rankings 是否可用')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (isAdmin) load()
  }, [isAdmin])

  const summary = data?.summary || {}
  const domains = data?.domains || []
  const topSkills = data?.topSkills || []
  const activeSkills = useMemo(
    () => [...topSkills].sort((a, b) => (b.apiCalls || 0) - (a.apiCalls || 0)).slice(0, 10),
    [topSkills]
  )

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

  return (
    <div className="flex-1 overflow-auto bg-gray-50">
      <div className="border-b border-gray-200 bg-white px-6 py-4">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h1 className="text-[18px] font-semibold text-gray-900">运营排行</h1>
            <p className="mt-1 text-[13px] text-gray-500">按领域、SKU 热度、API 活跃度汇总平台运行表现。</p>
          </div>
          <button
            type="button"
            onClick={load}
            disabled={loading}
            className="inline-flex h-8 items-center gap-1.5 rounded-md border border-gray-200 bg-white px-3 text-[12px] font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50"
          >
            <RefreshCcw size={14} className={loading ? 'animate-spin' : ''} />
            刷新
          </button>
        </div>
      </div>

      <div className="space-y-5 p-6">
        <div className="grid grid-cols-2 gap-3 xl:grid-cols-6">
          <Metric icon={BarChart3} label="SKU 总数" value={fmtNum(summary.totalSkills)} />
          <Metric icon={CheckCircle2} label="已上线" value={fmtNum(summary.publishedSkills)} tone="green" />
          <Metric icon={Download} label="下载" value={fmtNum(summary.downloads)} tone="blue" />
          <Metric icon={Zap} label="API 调用" value={fmtNum(summary.apiCalls)} tone="amber" />
          <Metric icon={Activity} label="成功率" value={fmtRate(summary.successRate)} tone="green" />
          <Metric icon={Trophy} label="平均延迟" value={`${fmtNum(summary.avgLatencyMs)} ms`} tone="gray" />
        </div>

        {loading && !data ? (
          <div className="rounded-lg border border-gray-200 bg-white px-6 py-16 text-center text-[13px] text-gray-400">加载运营数据中...</div>
        ) : error || (!domains.length && !topSkills.length) ? (
          <EmptyState error={error} onRetry={load} />
        ) : (
          <>
            <section className="overflow-hidden rounded-lg border border-gray-200 bg-white">
              <div className="flex items-center justify-between border-b border-gray-100 px-4 py-3">
                <div>
                  <h2 className="text-[14px] font-semibold text-gray-900">领域热点排行</h2>
                  <p className="mt-0.5 text-[12px] text-gray-500">按流程一级领域聚合 SKU、下载、点赞与 API 调用。</p>
                </div>
              </div>
              <div className="overflow-x-auto">
                <table className="min-w-full text-left text-[13px]">
                  <thead className="bg-gray-50 text-[12px] font-medium text-gray-500">
                    <tr>
                      <th className="px-4 py-3">排名</th>
                      <th className="px-4 py-3">领域</th>
                      <th className="px-4 py-3 text-right">SKU</th>
                      <th className="px-4 py-3 text-right">已上线</th>
                      <th className="px-4 py-3 text-right">下载</th>
                      <th className="px-4 py-3 text-right">API 调用</th>
                      <th className="px-4 py-3 text-right">成功率</th>
                      <th className="px-4 py-3 text-right">热度分</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100">
                    {domains.map((row, index) => (
                      <tr key={row.domain} className="hover:bg-gray-50/70">
                        <td className="px-4 py-3 text-gray-400">#{index + 1}</td>
                        <td className="px-4 py-3 font-medium text-gray-900">{row.domain}</td>
                        <td className="px-4 py-3 text-right tabular-nums text-gray-700">{fmtNum(row.totalSkills)}</td>
                        <td className="px-4 py-3 text-right tabular-nums text-emerald-700">{fmtNum(row.publishedSkills)}</td>
                        <td className="px-4 py-3 text-right tabular-nums text-gray-700">{fmtNum(row.downloads)}</td>
                        <td className="px-4 py-3 text-right tabular-nums text-gray-700">{fmtNum(row.apiCalls)}</td>
                        <td className="px-4 py-3 text-right tabular-nums text-gray-700">{fmtRate(row.successRate)}</td>
                        <td className="px-4 py-3 text-right tabular-nums font-semibold text-gray-900">{fmtNum(row.hotScore)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>

            <div className="grid gap-5 xl:grid-cols-[minmax(0,1.35fr)_minmax(360px,0.65fr)]">
              <section className="overflow-hidden rounded-lg border border-gray-200 bg-white">
                <div className="border-b border-gray-100 px-4 py-3">
                  <h2 className="text-[14px] font-semibold text-gray-900">SKU 热点排行</h2>
                  <p className="mt-0.5 text-[12px] text-gray-500">综合下载、点赞、点踩、API 调用形成热度分。</p>
                </div>
                <div className="overflow-x-auto">
                  <table className="min-w-full text-left text-[13px]">
                    <thead className="bg-gray-50 text-[12px] font-medium text-gray-500">
                      <tr>
                        <th className="px-4 py-3">排名</th>
                        <th className="px-4 py-3">SKU</th>
                        <th className="px-4 py-3">状态</th>
                        <th className="px-4 py-3 text-right">下载</th>
                        <th className="px-4 py-3 text-right">点赞</th>
                        <th className="px-4 py-3 text-right">API 调用</th>
                        <th className="px-4 py-3 text-right">热度分</th>
                        <th className="px-4 py-3 text-right">操作</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                      {topSkills.map((skill, index) => {
                        const skillId = skill.id
                        return (
                          <tr key={skill.id} className="hover:bg-gray-50/70">
                            <td className="px-4 py-3 text-gray-400">#{index + 1}</td>
                            <td className="px-4 py-3">
                              <div className="max-w-[360px] truncate font-medium text-gray-900">{skill.name}</div>
                              <div className="mt-0.5 max-w-[360px] truncate text-[12px] text-gray-500">{skill.nodePath || skill.domain}</div>
                            </td>
                            <td className="px-4 py-3"><StatusBadge status={skill.status} /></td>
                            <td className="px-4 py-3 text-right tabular-nums text-gray-700">{fmtNum(skill.downloads)}</td>
                            <td className="px-4 py-3 text-right tabular-nums text-gray-700">{fmtNum(skill.likes)}</td>
                            <td className="px-4 py-3 text-right tabular-nums text-gray-700">{fmtNum(skill.apiCalls)}</td>
                            <td className="px-4 py-3 text-right tabular-nums font-semibold text-gray-900">{fmtNum(skill.hotScore)}</td>
                            <td className="px-4 py-3 text-right">
                              <button
                                type="button"
                                onClick={() => openOverlay('sandbox', { skillId })}
                                disabled={!skill.hasPackage}
                                className="inline-flex h-7 items-center gap-1 rounded-md bg-gray-950 px-2.5 text-[12px] text-white hover:bg-gray-800 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400"
                              >
                                <Play size={13} />
                                运行
                              </button>
                            </td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
              </section>

              <section className="overflow-hidden rounded-lg border border-gray-200 bg-white">
                <div className="border-b border-gray-100 px-4 py-3">
                  <h2 className="text-[14px] font-semibold text-gray-900">API 活跃排行</h2>
                  <p className="mt-0.5 text-[12px] text-gray-500">按调用次数排序，适合排查热门调用和异常波动。</p>
                </div>
                <div className="divide-y divide-gray-100">
                  {activeSkills.map((skill, index) => {
                    const skillId = skill.id
                    return (
                      <div key={skill.id} className="flex items-center gap-3 px-4 py-3">
                        <div className="w-8 text-[12px] font-medium text-gray-400">#{index + 1}</div>
                        <div className="min-w-0 flex-1">
                          <div className="truncate text-[13px] font-medium text-gray-900">{skill.name}</div>
                          <div className="mt-0.5 truncate text-[12px] text-gray-500">{skill.domain} · {fmtRate(skill.successRate)} · {fmtNum(skill.avgLatencyMs)} ms</div>
                        </div>
                        <div className="text-right">
                          <div className="text-[13px] font-semibold tabular-nums text-gray-900">{fmtNum(skill.apiCalls)}</div>
                          <button
                            type="button"
                            onClick={() => openOverlay('sandbox', { skillId })}
                            disabled={!skill.hasPackage}
                            className="mt-1 inline-flex h-6 items-center gap-1 rounded border border-gray-200 px-2 text-[11px] text-gray-700 hover:bg-gray-50 disabled:cursor-not-allowed disabled:text-gray-300"
                          >
                            <Play size={12} />
                            运行
                          </button>
                        </div>
                      </div>
                    )
                  })}
                  {!activeSkills.length && (
                    <div className="px-4 py-10 text-center text-[13px] text-gray-400">暂无 API 调用记录</div>
                  )}
                </div>
              </section>
            </div>
          </>
        )}
      </div>
    </div>
  )
}
