"use client"

import { useState, useEffect, useCallback } from "react"
import { useTranslations } from "next-intl"
import { Activity, Users, AlertTriangle, Clock } from "lucide-react"
import { toast } from "sonner"

import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Progress } from "@/shared/components/ui/progress"
import { Button } from "@/shared/components/ui/button"
import { AiErrorBoundary } from "@/modules/ai/components/ai-error-boundary"
import { useAiClient } from "@/modules/ai/context/ai-client-provider"
import type { AiUsageStats } from "@/modules/ai/types"

/**
 * 管理员 AI 使用统计仪表盘
 *
 * 参考 Khanmigo district dashboard 和 Century Tech 全校视图。
 * 展示：
 * - 总调用数 / 今日 / 本周
 * - 活跃用户数
 * - 错误率
 * - 平均耗时
 * - 按能力分类
 * - 按角色分类
 * - 高频用户
 * - 最近活动
 */
export function AiUsageDashboard(): React.ReactNode {
  const t = useTranslations("ai")
  const aiClient = useAiClient()
  const [stats, setStats] = useState<AiUsageStats | null>(null)
  const [loading, setLoading] = useState(false)

  const loadStats = useCallback(async (): Promise<void> => {
    if (!aiClient.getAiUsageStats) return
    setLoading(true)
    try {
      const result = await aiClient.getAiUsageStats()
      if (result.success && result.data) {
        setStats(result.data)
      } else {
        toast.error(result.message ?? t("error.statsFailed"))
      }
    } catch {
      toast.error(t("error.statsFailed"))
    } finally {
      setLoading(false)
    }
  }, [aiClient, t])

  useEffect(() => {
    void loadStats()
  }, [loadStats])

  const statCards = stats
    ? [
        {
          label: t("admin.totalCalls"),
          value: stats.totalCalls.toString(),
          icon: Activity,
          color: "text-blue-500",
        },
        {
          label: t("admin.callsToday"),
          value: stats.callsToday.toString(),
          icon: Clock,
          color: "text-green-500",
        },
        {
          label: t("admin.activeUsers"),
          value: stats.activeUsers.toString(),
          icon: Users,
          color: "text-purple-500",
        },
        {
          label: t("admin.errorRate"),
          value: `${(stats.errorRate * 100).toFixed(1)}%`,
          icon: AlertTriangle,
          color: stats.errorRate > 0.05 ? "text-red-500" : "text-green-500",
        },
      ]
    : []

  return (
    <AiErrorBoundary>
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Activity className="h-4 w-4 text-primary" />
                {t("admin.usageDashboard")}
              </CardTitle>
              <CardDescription>{t("admin.dashboardDescription")}</CardDescription>
            </div>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => void loadStats()}
              disabled={loading}
            >
              {t("suggestion.regenerate")}
            </Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          {loading && !stats ? (
            <div className="grid grid-cols-2 gap-3">
              {[1, 2, 3, 4].map((i) => (
                <div key={i} className="h-20 rounded-md bg-muted animate-pulse" />
              ))}
            </div>
          ) : stats ? (
            <>
              {/* 统计卡片 */}
              <div className="grid grid-cols-2 gap-3">
                {statCards.map((card, index) => {
                  const Icon = card.icon
                  return (
                    <div key={index} className="rounded-md border p-3 space-y-1">
                      <div className="flex items-center justify-between">
                        <span className="text-xs text-muted-foreground">{card.label}</span>
                        <Icon className={`h-3.5 w-3.5 ${card.color}`} />
                      </div>
                      <p className="text-2xl font-bold">{card.value}</p>
                    </div>
                  )
                })}
              </div>

              {/* 按能力分类 */}
              {stats.byCapability.length > 0 ? (
                <div className="space-y-2">
                  <h4 className="text-sm font-medium">{t("admin.byCapability")}</h4>
                  <div className="space-y-2">
                    {stats.byCapability.map((item, index) => {
                      const maxCount = Math.max(...stats.byCapability.map((c) => c.count), 1)
                      const percent = (item.count / maxCount) * 100
                      return (
                        <div key={index} className="space-y-1">
                          <div className="flex items-center justify-between text-xs">
                            <span className="text-muted-foreground">{item.capability}</span>
                            <span className="font-medium">{item.count}</span>
                          </div>
                          <Progress value={percent} className="h-1.5" />
                        </div>
                      )
                    })}
                  </div>
                </div>
              ) : null}

              {/* 按角色分类 */}
              {stats.byRole.length > 0 ? (
                <div className="space-y-2">
                  <h4 className="text-sm font-medium">{t("admin.byRole")}</h4>
                  <div className="flex flex-wrap gap-2">
                    {stats.byRole.map((item, index) => (
                      <Badge key={index} variant="secondary" className="text-xs">
                        {item.role}: {item.count}
                      </Badge>
                    ))}
                  </div>
                </div>
              ) : null}

              {/* 高频用户 */}
              {stats.topUsers.length > 0 ? (
                <div className="space-y-2">
                  <h4 className="text-sm font-medium">{t("admin.topUsers")}</h4>
                  <div className="space-y-1">
                    {stats.topUsers.slice(0, 5).map((user, index) => (
                      <div key={index} className="flex items-center justify-between text-xs">
                        <span className="text-muted-foreground">{user.userId}</span>
                        <Badge variant="outline">{user.count}</Badge>
                      </div>
                    ))}
                  </div>
                </div>
              ) : null}

              {/* 最近活动 */}
              {stats.recentActivity.length > 0 ? (
                <div className="space-y-2">
                  <h4 className="text-sm font-medium">{t("admin.recentActivity")}</h4>
                  <div className="space-y-1 max-h-40 overflow-y-auto">
                    {stats.recentActivity.slice(0, 10).map((activity, index) => (
                      <div key={index} className="flex items-center justify-between text-xs border-b pb-1">
                        <span className="text-muted-foreground">{activity.capability}</span>
                        <div className="flex items-center gap-2">
                          <span className={activity.success ? "text-green-500" : "text-red-500"}>
                            {activity.success ? "✓" : "✗"}
                          </span>
                          <span className="text-muted-foreground">{activity.durationMs}ms</span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ) : null}

              {stats.totalCalls === 0 ? (
                <div className="text-center py-8 text-sm text-muted-foreground">
                  {t("admin.noData")}
                </div>
              ) : null}
            </>
          ) : (
            <div className="text-center py-8 text-sm text-muted-foreground">
              {t("admin.noData")}
            </div>
          )}
        </CardContent>
      </Card>
    </AiErrorBoundary>
  )
}
