/**
 * 平台总览页 — 企业数、员工数、套餐分布、最近注册企业
 */
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { Building2, Users, FileText, Calculator, TrendingUp } from 'lucide-react'
import { platformApi } from '../../lib/api-services'

interface DashboardData {
  totalOrgs: number
  totalUsers: number
  totalEmployees: number
  totalContracts: number
  activeContracts: number
  totalPayslips: number
  orgsByPlan: { plan: string; count: number }[]
  recentOrgs: {
    id: string; name: string; plan: string; city: string
    createdAt: string; maxEmployees: number
    employeeCount: number; userCount: number
  }[]
}

const PLAN_LABELS: Record<string, string> = { FREE: '免费版', PRO: '专业版', ENTERPRISE: '企业版' }
const PLAN_COLORS: Record<string, string> = { FREE: 'bg-gray-100 text-gray-700', PRO: 'bg-blue-50 text-blue-700', ENTERPRISE: 'bg-purple-50 text-purple-700' }

export default function PlatformDashboard() {
  const [data, setData] = useState<DashboardData | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    platformApi.dashboard().then((data: any) => setData(data)).finally(() => setLoading(false))
  }, [])

  if (loading) return <div className="text-center py-12 text-gray-400">加载中...</div>
  if (!data) return null

  const stats = [
    { label: '企业总数', value: data.totalOrgs, icon: Building2, color: 'text-primary' },
    { label: '用户总数', value: data.totalUsers, icon: Users, color: 'text-blue-600' },
    { label: '员工总数', value: data.totalEmployees, icon: Users, color: 'text-emerald-600' },
    { label: '有效合同', value: data.activeContracts, sub: `共 ${data.totalContracts} 份`, icon: FileText, color: 'text-purple-600' },
    { label: '工资条总数', value: data.totalPayslips, icon: Calculator, color: 'text-rose-600' },
  ]

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">数据总览</h1>
        <p className="text-sm text-gray-500 mt-1">平台全局数据看板</p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
        {stats.map((s) => {
          const Icon = s.icon
          return (
            <div key={s.label} className="bg-white border border-gray-200 rounded-lg p-4">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-gray-500">{s.label}</span>
                <Icon className={`w-5 h-5 ${s.color}`} />
              </div>
              <div className="text-2xl font-bold text-gray-900">{s.value.toLocaleString()}</div>
              {(s as any).sub && <div className="text-xs text-gray-400 mt-0.5">{(s as any).sub}</div>}
            </div>
          )
        })}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 套餐分布 */}
        <div className="bg-white border border-gray-200 rounded-lg p-5">
          <h2 className="text-sm font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <TrendingUp className="w-4 h-4 text-primary" />
            套餐分布
          </h2>
          <div className="space-y-3">
            {data.orgsByPlan.map((item) => (
              <div key={item.plan} className="flex items-center justify-between">
                <span className={`px-2 py-0.5 rounded text-xs font-medium ${PLAN_COLORS[item.plan] || 'bg-gray-100 text-gray-700'}`}>
                  {PLAN_LABELS[item.plan] || item.plan}
                </span>
                <div className="flex items-center gap-2 flex-1 ml-3">
                  <div className="flex-1 h-2 bg-gray-100 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-primary rounded-full"
                      style={{ width: `${data.totalOrgs > 0 ? (item.count / data.totalOrgs) * 100 : 0}%` }}
                    />
                  </div>
                  <span className="text-sm text-gray-700 w-8 text-right">{item.count}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 最近注册企业 */}
        <div className="bg-white border border-gray-200 rounded-lg p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-semibold text-gray-900">最近注册企业</h2>
            <Link to="/platform/orgs" className="text-xs text-primary hover:underline">查看全部 →</Link>
          </div>
          <div className="space-y-2">
            {data.recentOrgs.map((org) => (
              <Link
                key={org.id}
                to={`/platform/orgs?id=${org.id}`}
                className="flex items-center justify-between p-2 rounded-md hover:bg-gray-50 transition-colors"
              >
                <div className="min-w-0">
                  <div className="text-sm text-gray-900 truncate">{org.name}</div>
                  <div className="text-xs text-gray-400">{org.city || '未设置'} · {org.employeeCount} 员工</div>
                </div>
                <span className={`px-2 py-0.5 rounded text-xs font-medium shrink-0 ${PLAN_COLORS[org.plan] || 'bg-gray-100 text-gray-700'}`}>
                  {PLAN_LABELS[org.plan] || org.plan}
                </span>
              </Link>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}
