"use client";

import { useQuery } from "@tanstack/react-query";
import { api } from "@/lib/api/apiClient";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Skeleton } from "@/components/ui/skeleton";
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Legend,
  Tooltip,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
} from "recharts";
import {
  Activity,
  CheckCircle2,
  XCircle,
  Clock,
  Loader2,
  Timer,
  TrendingUp,
} from "lucide-react";

interface TaskStats {
  total: number;
  by_status: Record<string, number>;
  by_type: Record<string, number>;
  by_provider: Record<string, number>;
  avg_processing_time?: number;
  success_rate: number;
}

async function fetchTaskStats(): Promise<TaskStats> {
  const response = await api.get("/api/v1/admin/tasks/stats");
  const data = response.data?.data ?? response.data;
  return data as TaskStats;
}

const COLORS = {
  blue: "#3b82f6",
  green: "#22c55e",
  yellow: "#eab308",
  red: "#ef4444",
  purple: "#a855f7",
  orange: "#f97316",
  cyan: "#06b6d4",
  pink: "#ec4899",
};

const statusColors: Record<string, string> = {
  pending: COLORS.yellow,
  processing: COLORS.blue,
  success: COLORS.green,
  failed: COLORS.red,
  cancelled: COLORS.purple,
};

const statusLabels: Record<string, string> = {
  pending: "等待中",
  processing: "处理中",
  success: "成功",
  failed: "失败",
  cancelled: "已取消",
};

const typeLabels: Record<string, string> = {
  image: "图片生成",
  video: "视频生成",
  audio: "音频生成",
  music: "音乐生成",
  script: "剧本处理",
  other: "其他",
};

export default function TaskStatsPage() {
  const { data: stats, isLoading } = useQuery({
    queryKey: ["admin", "tasks", "stats"],
    queryFn: fetchTaskStats,
    staleTime: 30 * 1000,
    refetchInterval: 60 * 1000,
  });

  if (isLoading) {
    return (
      <div className="container mx-auto py-6 space-y-6">
        <Skeleton className="h-8 w-48" />
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-32" />
          ))}
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Skeleton className="h-96" />
          <Skeleton className="h-96" />
        </div>
      </div>
    );
  }

  if (!stats) {
    return (
      <div className="container mx-auto py-6">
        <div className="text-center py-20">
          <Activity className="h-16 w-16 text-muted-foreground mx-auto mb-4" />
          <h2 className="text-xl font-semibold text-muted-foreground">
            暂无统计数据
          </h2>
        </div>
      </div>
    );
  }

  // Prepare chart data
  const statusData = Object.entries(stats.by_status).map(([key, value]) => ({
    name: statusLabels[key] || key,
    value,
    color: statusColors[key] || COLORS.blue,
  }));

  const typeData = Object.entries(stats.by_type).map(([key, value]) => ({
    name: typeLabels[key] || key,
    value,
  }));

  const providerData = Object.entries(stats.by_provider).map(([key, value]) => ({
    name: key || "未知",
    value,
  }));

  const statCards = [
    {
      title: "总任务数",
      value: stats.total,
      icon: Activity,
      color: "text-blue-500",
      bgColor: "bg-blue-500/10",
    },
    {
      title: "成功率",
      value: `${stats.success_rate.toFixed(1)}%`,
      icon: TrendingUp,
      color: "text-green-500",
      bgColor: "bg-green-500/10",
    },
    {
      title: "平均处理时间",
      value: stats.avg_processing_time
        ? `${Math.round(stats.avg_processing_time)}秒`
        : "-",
      icon: Timer,
      color: "text-purple-500",
      bgColor: "bg-purple-500/10",
    },
    {
      title: "进行中任务",
      value: stats.by_status.processing || 0,
      icon: Loader2,
      color: "text-orange-500",
      bgColor: "bg-orange-500/10",
    },
  ];

  return (
    <div className="container mx-auto py-6 space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold tracking-tight">任务统计</h1>
        <p className="text-muted-foreground">查看任务执行情况和性能指标</p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {statCards.map((card) => (
          <Card key={card.title}>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-muted-foreground">
                    {card.title}
                  </p>
                  <p className="text-3xl font-bold mt-2">{card.value}</p>
                </div>
                <div className={`p-3 rounded-lg ${card.bgColor}`}>
                  <card.icon className={`h-6 w-6 ${card.color}`} />
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Status Distribution */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Activity className="h-5 w-5" />
              任务状态分布
            </CardTitle>
          </CardHeader>
          <CardContent>
            {statusData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <PieChart>
                  <Pie
                    data={statusData}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={100}
                    paddingAngle={5}
                    dataKey="value"
                    label={({ name, value }) => `${name}: ${value}`}
                    labelLine={false}
                  >
                    {statusData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-[300px] flex items-center justify-center text-muted-foreground">
                暂无数据
              </div>
            )}
            <div className="grid grid-cols-3 gap-2 mt-4">
              {statusData.map((item) => (
                <div key={item.name} className="flex items-center gap-2">
                  <div
                    className="w-3 h-3 rounded-full"
                    style={{ backgroundColor: item.color }}
                  />
                  <span className="text-sm text-muted-foreground">{item.name}</span>
                  <span className="text-sm font-medium ml-auto">{item.value}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Type Distribution */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Activity className="h-5 w-5" />
              任务类型分布
            </CardTitle>
          </CardHeader>
          <CardContent>
            {typeData.length > 0 ? (
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={typeData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Bar dataKey="value" fill={COLORS.blue} radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-[300px] flex items-center justify-center text-muted-foreground">
                暂无数据
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Provider Stats */}
      {providerData.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Activity className="h-5 w-5" />
              提供商分布
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {providerData.map((item) => {
                const percentage = stats.total > 0 ? (item.value / stats.total) * 100 : 0;
                return (
                  <div key={item.name} className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-muted-foreground">{item.name}</span>
                      <span className="font-medium">
                        {item.value} ({percentage.toFixed(1)}%)
                      </span>
                    </div>
                    <Progress value={percentage} className="h-2" />
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
