import { Navigate, useNavigate } from 'react-router-dom'
import { ArrowRight, BarChart3, BookOpen, Download, Key, Package, ScrollText, ShieldCheck, SlidersHorizontal, Users } from 'lucide-react'
import { useAuth } from '../contexts/AuthContext.jsx'
import { FEATURES } from '../featureFlags.js'
import { downloadSourceCode } from '../services/api.js'

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

const ITEMS = [
  {
    title: '运营排行',
    desc: '按流程领域查看热点、下载和 API 活跃排行。',
    to: '/skill-ops',
    icon: BarChart3,
    superOnly: true,
    scope: '超级管理员',
  },
  {
    title: '用户管理',
    desc: '注册用户、角色和账号权限。',
    to: '/user-management',
    icon: Users,
    superOnly: true,
    scope: '超级管理员',
  },
  {
    title: '操作日志',
    desc: '关键操作记录、审计和问题回溯。',
    to: '/audit-log',
    icon: ScrollText,
    superOnly: true,
    scope: '超级管理员',
  },
  {
    title: '智能体配置',
    desc: '智能体、模型服务商和运行时注册。',
    to: '/llm-settings',
    icon: Key,
    flag: 'llmSettings',
    scope: '管理员',
  },
  {
    title: '方案文档',
    desc: '平台架构、数据模型和产品说明。',
    to: '/architecture',
    icon: BookOpen,
    superOnly: true,
    scope: '超级管理员',
  },
]

export default function PlatformGovernance() {
  const { user } = useAuth()
  const navigate = useNavigate()
  const isSuperAdmin = user?.email === SUPER_ADMIN_EMAIL || user?.phone === SUPER_ADMIN_PHONE
  const isAdmin = user?.role === 'admin' || isSuperAdmin

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

  const visibleItems = ITEMS.filter(item => {
    if (item.flag && !FEATURES[item.flag]) return false
    if (item.superOnly) return isSuperAdmin
    return true
  })

  async function handleDownloadSource() {
    try {
      await downloadSourceCode()
    } catch {
      alert('下载失败，请检查权限或稍后重试')
    }
  }

  return (
    <div className="min-h-full bg-gray-50">
      <div className="border-b border-gray-200 bg-white px-6 py-4">
        <div className="mx-auto flex max-w-6xl flex-wrap items-start justify-between gap-4">
          <div>
            <div className="flex items-center gap-2 text-[12px] text-gray-500">
              <ShieldCheck size={14} className="text-brand-600" />
              <span>治理</span>
            </div>
            <h1 className="mt-1 text-[20px] font-semibold text-gray-950">平台治理</h1>
            <p className="mt-1 text-[13px] text-gray-500">管理能力统一收口，业务侧保留 Skill 与知识两条主线。</p>
          </div>
          <div className="flex h-10 w-10 items-center justify-center rounded-md bg-gray-950 text-white">
            <SlidersHorizontal size={18} />
          </div>
        </div>
      </div>

      <div className="mx-auto max-w-6xl p-6">
        <div className="mb-4 grid grid-cols-1 gap-3 md:grid-cols-3">
          <GovernanceStat label="治理入口" value={visibleItems.length + (isSuperAdmin ? 1 : 0)} />
          <GovernanceStat label="当前权限" value={isSuperAdmin ? '超级管理员' : '管理员'} />
          <GovernanceStat label="业务入口" value="2 条主线" />
        </div>

        <section className="overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm shadow-slate-200/40">
          <div className="grid grid-cols-[minmax(0,1fr)_88px] gap-3 border-b border-gray-100 bg-gray-50 px-4 py-2.5 text-[12px] font-medium text-gray-500 sm:grid-cols-[minmax(0,1fr)_120px_88px]">
            <div>能力</div>
            <div className="hidden text-center sm:block">权限</div>
            <div className="text-right">进入</div>
          </div>
          <div className="divide-y divide-gray-100">
            {visibleItems.map(item => {
            const Icon = item.icon
            return (
              <button
                key={item.to}
                onClick={() => navigate(item.to)}
                  className="group grid w-full grid-cols-[minmax(0,1fr)_88px] items-center gap-3 px-4 py-4 text-left transition hover:bg-gray-50 sm:grid-cols-[minmax(0,1fr)_120px_88px]"
              >
                  <div className="flex min-w-0 items-center gap-3">
                    <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md bg-gray-100 text-gray-700 group-hover:bg-brand-50 group-hover:text-brand-700">
                    <Icon size={18} />
                    </div>
                    <div className="min-w-0">
                      <div className="truncate text-[15px] font-semibold text-gray-950">{item.title}</div>
                      <div className="mt-0.5 truncate text-[13px] text-gray-500">{item.desc}</div>
                    </div>
                  </div>
                  <div className="hidden justify-center sm:flex">
                    <span className="rounded-full bg-gray-100 px-2 py-0.5 text-[11px] text-gray-600">{item.scope || '管理员'}</span>
                  </div>
                  <div className="flex justify-end text-gray-400 group-hover:text-gray-900">
                    <ArrowRight size={17} />
                  </div>
              </button>
            )
          })}
            {isSuperAdmin && (
              <button
                onClick={handleDownloadSource}
                className="group grid w-full grid-cols-[minmax(0,1fr)_88px] items-center gap-3 px-4 py-4 text-left transition hover:bg-gray-50 sm:grid-cols-[minmax(0,1fr)_120px_88px]"
              >
                <div className="flex min-w-0 items-center gap-3">
                  <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md bg-gray-100 text-gray-700 group-hover:bg-amber-50 group-hover:text-amber-700">
                    <Package size={18} />
                  </div>
                  <div className="min-w-0">
                    <div className="truncate text-[15px] font-semibold text-gray-950">项目代码</div>
                    <div className="mt-0.5 truncate text-[13px] text-gray-500">源码备份与交付包下载。</div>
                  </div>
                </div>
                <div className="hidden justify-center sm:flex">
                  <span className="rounded-full bg-gray-100 px-2 py-0.5 text-[11px] text-gray-600">超级管理员</span>
                </div>
                <div className="flex justify-end text-gray-400 group-hover:text-gray-900">
                  <Download size={17} />
                </div>
              </button>
            )}
          </div>
        </section>
      </div>
    </div>
  )
}

function GovernanceStat({ label, value }) {
  return (
    <div className="rounded-lg border border-gray-200 bg-white px-4 py-3">
      <div className="text-[12px] text-gray-500">{label}</div>
      <div className="mt-1 text-[18px] font-semibold text-gray-950">{value}</div>
    </div>
  )
}
