/**
 * 系统健康监控仪表板（管理员）
 *
 * 统一展示：
 * - 错误日志（error_logs）：近 24h 错误数 / 严重度分布 / 最近列表
 * - 性能指标（perf_logs）：API/页面平均耗时 / P95 / 慢请求 Top
 * - Agent 测试结果（agent_test_results）：通过率 / 失败样本
 *
 * 路由：/admin/system-health
 * 权限：AdminProtectedRoute（已在 App.tsx 中包裹 /admin/*）
 *
 * 实现说明：纯前端聚合，所有查询走 supabase 客户端 + RLS
 * （error_logs/perf_logs 已限制 admin SELECT，agent_test_results 公开 SELECT）
 */
import { useEffect, useMemo, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { supabase } from "@/integrations/supabase/client";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import {
  Activity,
  AlertTriangle,
  Gauge,
  RefreshCw,
  CheckCircle2,
  XCircle,
  Zap,
} from "lucide-react";
import { AdminSubpageHeader } from "@/components/admin/AdminSubpageHeader";

interface ErrorLog {
  id: string;
  message: string;
  severity: string;
  url: string | null;
  created_at: string;
  context: any;
}

interface PerfLog {
  id: string;
  metric_type: string;
  metric_name: string;
  duration_ms: number;
  url: string | null;
  created_at: string;
  context: any;
}

interface TestResult {
  id: string;
  agent_type: string;
  user_message: string;
  passed: boolean;
  issues: string[] | null;
  trace_id: string;
  created_at: string;
}

const SEVERITY_COLOR: Record<string, string> = {
  fatal: "bg-destructive text-destructive-foreground",
  error: "bg-destructive/80 text-destructive-foreground",
  warning: "bg-warning text-warning-foreground",
  info: "bg-muted text-muted-foreground",
};

function percentile(values: number[], p: number): number {
  if (!values.length) return 0;
  const sorted = [...values].sort((a, b) => a - b);
  const idx = Math.min(sorted.length - 1, Math.floor(sorted.length * p));
  return sorted[idx];
}

export default function SystemHealthPage() {
  const [loading, setLoading] = useState(true);
  const [errors, setErrors] = useState<ErrorLog[]>([]);
  const [perfs, setPerfs] = useState<PerfLog[]>([]);
  const [tests, setTests] = useState<TestResult[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const load = async () => {
    setRefreshing(true);
    const since = new Date(Date.now() - 24 * 3600 * 1000).toISOString();
    const [errRes, perfRes, testRes] = await Promise.all([
      supabase
        .from("error_logs")
        .select("id,message,severity,url,created_at,context")
        .gte("created_at", since)
        .order("created_at", { ascending: false })
        .limit(200),
      supabase
        .from("perf_logs")
        .select("id,metric_type,metric_name,duration_ms,url,created_at,context")
        .gte("created_at", since)
        .order("created_at", { ascending: false })
        .limit(500),
      supabase
        .from("agent_test_results")
        .select("id,agent_type,user_message,passed,issues,trace_id,created_at")
        .order("created_at", { ascending: false })
        .limit(50),
    ]);
    setErrors((errRes.data as ErrorLog[]) ?? []);
    setPerfs((perfRes.data as PerfLog[]) ?? []);
    setTests((testRes.data as TestResult[]) ?? []);
    setLoading(false);
    setRefreshing(false);
  };

  useEffect(() => {
    load();
  }, []);

  // ===== 聚合统计 =====
  const errStats = useMemo(() => {
    const bySeverity: Record<string, number> = {};
    errors.forEach((e) => {
      bySeverity[e.severity] = (bySeverity[e.severity] ?? 0) + 1;
    });
    return { total: errors.length, bySeverity };
  }, [errors]);

  const perfStats = useMemo(() => {
    const apiCalls = perfs.filter((p) => p.metric_type === "api_call");
    const pageLoads = perfs.filter((p) => p.metric_type === "page_load");
    const slow = perfs.filter((p) => p.duration_ms >= 1000);

    const byName: Record<string, number[]> = {};
    apiCalls.forEach((p) => {
      (byName[p.metric_name] ??= []).push(p.duration_ms);
    });
    const apiTop = Object.entries(byName)
      .map(([name, arr]) => ({
        name,
        count: arr.length,
        avg: Math.round(arr.reduce((s, n) => s + n, 0) / arr.length),
        p95: Math.round(percentile(arr, 0.95)),
      }))
      .sort((a, b) => b.p95 - a.p95)
      .slice(0, 8);

    return {
      apiCount: apiCalls.length,
      pageCount: pageLoads.length,
      slowCount: slow.length,
      apiTop,
      slowList: slow.slice(0, 10),
    };
  }, [perfs]);

  const testStats = useMemo(() => {
    const passed = tests.filter((t) => t.passed).length;
    return {
      total: tests.length,
      passed,
      failed: tests.length - passed,
      passRate: tests.length ? Math.round((passed / tests.length) * 100) : 0,
    };
  }, [tests]);

  if (loading) {
    return (
      <div className="p-6 space-y-4">
        <Skeleton className="h-10 w-64" />
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          {[0, 1, 2, 3].map((i) => (
            <Skeleton key={i} className="h-28" />
          ))}
        </div>
        <Skeleton className="h-96" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background flex flex-col">
      <AdminSubpageHeader
        title="系统健康"
        scope="system-health"
        fallback={{ path: "/admin/me", label: "我的" }}
        actions={
          <Button
            variant="outline"
            size="sm"
            onClick={load}
            disabled={refreshing}
          >
            <RefreshCw className={`h-4 w-4 mr-2 ${refreshing ? "animate-spin" : ""}`} />
            刷新
          </Button>
        }
      />
      <div className="p-6 space-y-6">
        {/* 页头 */}
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Activity className="h-6 w-6 text-primary" />
            系统健康监控
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            最近 24 小时的错误、性能与 Agent 健康指标
          </p>
        </div>

      {/* 概览卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardDescription className="flex items-center gap-1.5">
              <AlertTriangle className="h-4 w-4 text-destructive" /> 错误总数 (24h)
            </CardDescription>
            <CardTitle className="text-3xl">{errStats.total}</CardTitle>
          </CardHeader>
          <CardContent className="flex flex-wrap gap-1">
            {Object.entries(errStats.bySeverity).map(([sev, n]) => (
              <Badge key={sev} className={SEVERITY_COLOR[sev] ?? ""}>
                {sev}: {n}
              </Badge>
            ))}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardDescription className="flex items-center gap-1.5">
              <Gauge className="h-4 w-4 text-primary" /> API 调用 (24h)
            </CardDescription>
            <CardTitle className="text-3xl">{perfStats.apiCount}</CardTitle>
          </CardHeader>
          <CardContent className="text-xs text-muted-foreground">
            页面加载: {perfStats.pageCount} 次
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardDescription className="flex items-center gap-1.5">
              <Zap className="h-4 w-4 text-amber-500" /> 慢请求 (≥1s)
            </CardDescription>
            <CardTitle className="text-3xl">{perfStats.slowCount}</CardTitle>
          </CardHeader>
          <CardContent className="text-xs text-muted-foreground">
            占比{" "}
            {perfStats.apiCount + perfStats.pageCount > 0
              ? Math.round(
                  (perfStats.slowCount /
                    (perfStats.apiCount + perfStats.pageCount)) *
                    100,
                )
              : 0}
            %
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardDescription className="flex items-center gap-1.5">
              <CheckCircle2 className="h-4 w-4 text-emerald-500" /> Agent 通过率
            </CardDescription>
            <CardTitle className="text-3xl">{testStats.passRate}%</CardTitle>
          </CardHeader>
          <CardContent className="text-xs text-muted-foreground">
            {testStats.passed}/{testStats.total} 通过
          </CardContent>
        </Card>
      </div>

      {/* 详细 Tabs */}
      <Tabs defaultValue="errors">
        <TabsList>
          <TabsTrigger value="errors">错误日志</TabsTrigger>
          <TabsTrigger value="perf">性能 / 慢请求</TabsTrigger>
          <TabsTrigger value="agents">Agent 测试</TabsTrigger>
        </TabsList>

        {/* 错误日志 */}
        <TabsContent value="errors">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">最近错误</CardTitle>
              <CardDescription>按时间倒序，最多 200 条</CardDescription>
            </CardHeader>
            <CardContent>
              <ScrollArea className="h-[480px]">
                <div className="space-y-2">
                  {errors.length === 0 ? (
                    <p className="text-sm text-muted-foreground text-center py-12">
                      🎉 24 小时内无错误日志
                    </p>
                  ) : (
                    errors.map((e) => (
                      <div
                        key={e.id}
                        className="border rounded-md p-3 hover:bg-muted/40 transition-colors"
                      >
                        <div className="flex items-start justify-between gap-3">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <Badge
                                className={SEVERITY_COLOR[e.severity] ?? ""}
                              >
                                {e.severity}
                              </Badge>
                              {e.context?.source && (
                                <Badge variant="outline" className="text-[10px]">
                                  {e.context.source}
                                </Badge>
                              )}
                              <span className="text-xs text-muted-foreground">
                                {formatDistanceToNow(new Date(e.created_at), {
                                  addSuffix: true,
                                  locale: zhCN,
                                })}
                              </span>
                            </div>
                            <p className="text-sm font-mono break-all">
                              {e.message}
                            </p>
                            {e.url && (
                              <p className="text-xs text-muted-foreground mt-1 truncate">
                                {e.url}
                              </p>
                            )}
                          </div>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </ScrollArea>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 性能 */}
        <TabsContent value="perf" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">API 调用 P95 排行</CardTitle>
              <CardDescription>
                按 95 分位耗时排序，识别最慢的接口
              </CardDescription>
            </CardHeader>
            <CardContent>
              {perfStats.apiTop.length === 0 ? (
                <p className="text-sm text-muted-foreground py-6 text-center">
                  暂无 API 调用数据
                </p>
              ) : (
                <div className="space-y-1.5">
                  {perfStats.apiTop.map((row) => (
                    <div
                      key={row.name}
                      className="flex items-center justify-between text-sm border-b pb-1.5"
                    >
                      <span className="font-mono truncate flex-1">{row.name}</span>
                      <div className="flex items-center gap-3 text-xs">
                        <span className="text-muted-foreground">
                          n={row.count}
                        </span>
                        <span>avg {row.avg}ms</span>
                        <Badge
                          variant={row.p95 >= 1000 ? "destructive" : "secondary"}
                        >
                          P95 {row.p95}ms
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="text-base">慢请求样本（≥1s）</CardTitle>
            </CardHeader>
            <CardContent>
              {perfStats.slowList.length === 0 ? (
                <p className="text-sm text-muted-foreground py-6 text-center">
                  ✨ 无慢请求
                </p>
              ) : (
                <div className="space-y-1.5">
                  {perfStats.slowList.map((p) => (
                    <div
                      key={p.id}
                      className="flex items-center justify-between text-xs border rounded-md px-2 py-1.5"
                    >
                      <span className="font-mono truncate flex-1">
                        [{p.metric_type}] {p.metric_name}
                      </span>
                      <Badge variant="destructive" className="ml-2">
                        {p.duration_ms}ms
                      </Badge>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Agent 测试 */}
        <TabsContent value="agents">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Agent 最近测试</CardTitle>
              <CardDescription>
                由 agent_test_results 表自动收集，最多保留 100 条
              </CardDescription>
            </CardHeader>
            <CardContent>
              <ScrollArea className="h-[480px]">
                <div className="space-y-2">
                  {tests.length === 0 ? (
                    <p className="text-sm text-muted-foreground text-center py-12">
                      暂无 Agent 测试数据
                    </p>
                  ) : (
                    tests.map((t) => (
                      <div
                        key={t.id}
                        className="border rounded-md p-3 hover:bg-muted/40 transition-colors"
                      >
                        <div className="flex items-start gap-2">
                          {t.passed ? (
                            <CheckCircle2 className="h-4 w-4 text-emerald-500 mt-0.5 shrink-0" />
                          ) : (
                            <XCircle className="h-4 w-4 text-destructive mt-0.5 shrink-0" />
                          )}
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <Badge variant="outline">{t.agent_type}</Badge>
                              <span className="text-xs text-muted-foreground">
                                {formatDistanceToNow(new Date(t.created_at), {
                                  addSuffix: true,
                                  locale: zhCN,
                                })}
                              </span>
                            </div>
                            <p className="text-sm">{t.user_message}</p>
                            {t.issues && t.issues.length > 0 && (
                              <div className="mt-1 flex flex-wrap gap-1">
                                {t.issues.map((iss, i) => (
                                  <Badge
                                    key={i}
                                    variant="destructive"
                                    className="text-[10px]"
                                  >
                                    {iss}
                                  </Badge>
                                ))}
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </ScrollArea>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
      </div>
    </div>
  );
}
