/**
 * 任务历史页面 — V21 设计系统
 * 页面头部 + 圆角胶囊 Tab 筛选（含计数）+ 卡片式任务列表 + 分页 + 空状态
 * 使用 useQuery 对接后端真实 API（api/tasks.ts）
 */
import React, { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui";
import { getUserTasks, retryTask, type TaskItem } from "@/api/tasks";
import "./history.css";

/* ============================================================
 * 类型 & 常量
 * ============================================================ */
type TaskStatus = "completed" | "processing" | "pending" | "failed";

const statusLabel: Record<TaskStatus, string> = {
  completed: "已完成",
  processing: "进行中",
  pending: "排队中",
  failed: "失败",
};

/** 将后端 status 字符串映射为前端 TaskStatus */
const normalizeStatus = (s: string): TaskStatus => {
  const map: Record<string, TaskStatus> = {
    completed: "completed",
    succeeded: "completed",
    success: "completed",
    processing: "processing",
    running: "processing",
    pending: "pending",
    queued: "pending",
    failed: "failed",
    error: "failed",
  };
  return map[s] ?? "pending";
};

/** 格式化日期 */
const formatDate = (iso?: string | null): string => {
  if (!iso) return "—";
  const d = new Date(iso);
  if (isNaN(d.getTime())) return "—";
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
};

/* ============================================================
 * Tab 配置
 * ============================================================ */
interface TabConfig {
  key: string;
  label: string;
  statusFilter?: TaskStatus;
}

const tabs: TabConfig[] = [
  { key: "all", label: "全部" },
  { key: "processing", label: "进行中", statusFilter: "processing" },
  { key: "completed", label: "已完成", statusFilter: "completed" },
  { key: "failed", label: "失败", statusFilter: "failed" },
];

/* ============================================================
 * 分页配置
 * ============================================================ */
const PAGE_SIZE = 10;

/* ============================================================
 * 组件
 * ============================================================ */
const TaskHistory: React.FC = () => {
  const [activeTab, setActiveTab] = useState("all");
  const [currentPage, setCurrentPage] = useState(1);
  const queryClient = useQueryClient();

  // ── 获取任务列表 ──
  const {
    data: tasks = [],
    isLoading,
    isError,
    error,
    refetch,
  } = useQuery<TaskItem[], Error>({
    queryKey: ["tasks"],
    queryFn: getUserTasks,
    staleTime: 30_000,
  });

  // ── 重试任务 mutation ──
  const retryMutation = useMutation({
    mutationFn: retryTask,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["tasks"] });
    },
  });

  // 将后端数据映射为页面展示用的结构
  const mappedTasks = tasks.map((t) => ({
    id: t.id,
    name: t.user_message || t.task_type,
    type: t.task_type,
    template: t.template_id,
    status: normalizeStatus(t.status),
    date: formatDate(t.created_at),
    duration: undefined as string | undefined,
    progress: t.progress,
    retryable: t.retryable,
    errorMessage: t.error_message,
  }));

  // 获取当前 Tab 的筛选状态
  const currentTab = tabs.find((t) => t.key === activeTab);
  const statusFilter = currentTab?.statusFilter;

  // 过滤任务
  const filteredTasks = statusFilter
    ? mappedTasks.filter((t) => t.status === statusFilter)
    : mappedTasks;

  // 计算各 Tab 的数量
  const tabCounts: Record<string, number> = {
    all: mappedTasks.length,
    processing: mappedTasks.filter((t) => t.status === "processing").length,
    completed: mappedTasks.filter((t) => t.status === "completed").length,
    failed: mappedTasks.filter((t) => t.status === "failed").length,
  };

  // 分页
  const totalPages = Math.ceil(filteredTasks.length / PAGE_SIZE);
  const paginatedTasks = filteredTasks.slice(
    (currentPage - 1) * PAGE_SIZE,
    currentPage * PAGE_SIZE,
  );

  // 切换 Tab 时重置页码
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setCurrentPage(1);
  };

  // 重试任务
  const handleRetry = (taskId: string) => {
    retryMutation.mutate(taskId);
  };

  // 查看任务详情
  const handleView = (taskId: string) => {
    // TODO: 跳转到任务详情页（待路由实现）
    console.log("查看任务:", taskId);
  };

  // ── Loading 状态 ──
  if (isLoading) {
    return (
      <div className="xx-history-page">
        <div className="xx-history-header">
          <h2>任务历史</h2>
          <p>查看和管理所有生成任务</p>
        </div>
        <div className="xx-history-empty">
          <div className="xx-history-empty-icon">⏳</div>
          <h3>加载中...</h3>
        </div>
      </div>
    );
  }

  // ── Error 状态 ──
  if (isError) {
    return (
      <div className="xx-history-page">
        <div className="xx-history-header">
          <h2>任务历史</h2>
          <p>查看和管理所有生成任务</p>
        </div>
        <div className="xx-history-empty">
          <div className="xx-history-empty-icon">❌</div>
          <h3>加载失败</h3>
          <p>{error?.message || "网络异常，请稍后重试"}</p>
          <Button
            buttonType="primary"
            buttonSize="md"
            onClick={() => refetch()}
          >
            重新加载
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="xx-history-page">
      {/* ── 页面头部 ──────────────────────────────────────────── */}
      <div className="xx-history-header">
        <h2>任务历史</h2>
        <p>查看和管理所有生成任务</p>
      </div>

      {/* ── Tab 切换 ──────────────────────────────────────────── */}
      <div className="xx-history-tabs">
        {tabs.map((tab) => (
          <button
            key={tab.key}
            className={`xx-history-tab${activeTab === tab.key ? " active" : ""}`}
            onClick={() => handleTabChange(tab.key)}
          >
            {tab.label}
            <span className="xx-history-tab-count">{tabCounts[tab.key]}</span>
          </button>
        ))}
      </div>

      {/* ── 任务列表 ──────────────────────────────────────────── */}
      {paginatedTasks.length === 0 ? (
        <div className="xx-history-empty">
          <div className="xx-history-empty-icon">📭</div>
          <h3>暂无任务记录</h3>
          <p>
            {activeTab === "all"
              ? "点击上方按钮开始创建任务"
              : "当前分类下没有任务"}
          </p>
        </div>
      ) : (
        <div className="xx-history-task-list">
          {paginatedTasks.map((task) => (
            <div key={task.id} className="xx-history-task-item">
              {/* 任务信息 */}
              <div className="xx-history-task-info">
                <h4>{task.name}</h4>
                <span>
                  {task.type} · 模板：{task.template}
                </span>
              </div>

              {/* 状态标签 */}
              <span
                className={`xx-history-status xx-history-status--${task.status}`}
              >
                {statusLabel[task.status]}
              </span>

              {/* 时间区 */}
              <div className="xx-history-task-time">
                <span>{task.date}</span>
                {task.status === "completed" ? (
                  <span>完成</span>
                ) : task.status === "processing" ? (
                  <span>进度 {task.progress}%</span>
                ) : task.status === "failed" ? (
                  <span>{task.errorMessage || "请重试"}</span>
                ) : (
                  <span>等待中</span>
                )}
              </div>

              {/* 操作按钮 */}
              <div className="xx-history-task-action">
                {task.status === "failed" && task.retryable ? (
                  <Button
                    buttonType="ghost"
                    buttonSize="sm"
                    onClick={() => handleRetry(task.id)}
                    disabled={retryMutation.isPending}
                  >
                    {retryMutation.isPending ? "重试中..." : "重试"}
                  </Button>
                ) : (
                  <Button
                    buttonType="ghost"
                    buttonSize="sm"
                    onClick={() => handleView(task.id)}
                  >
                    查看
                  </Button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* ── 分页 ──────────────────────────────────────────────── */}
      {totalPages > 1 && (
        <div className="xx-history-pagination">
          <button
            className="xx-history-page-btn"
            disabled={currentPage === 1}
            onClick={() => setCurrentPage(currentPage - 1)}
          >
            ‹
          </button>
          {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
            <button
              key={page}
              className={`xx-history-page-btn${currentPage === page ? " active" : ""}`}
              onClick={() => setCurrentPage(page)}
            >
              {page}
            </button>
          ))}
          <button
            className="xx-history-page-btn"
            disabled={currentPage === totalPages}
            onClick={() => setCurrentPage(currentPage + 1)}
          >
            ›
          </button>
          <span className="xx-history-page-info">
            共 {filteredTasks.length} 条
          </span>
        </div>
      )}
    </div>
  );
};

export default TaskHistory;
