/**
 * 控制台页面 — V21 设计系统
 * KPI 卡片网格 + 快速入口 + 最近任务卡片列表 + 使用统计图表 + 公告
 * 使用 mock 数据，CSS 变量，V21 组件
 */
import React from "react";
import { useNavigate } from "react-router-dom";
import { Button, Tag } from "@/components/ui";
import {
  VideoCameraOutlined,
  AppstoreOutlined,
  ThunderboltOutlined,
  DatabaseOutlined,
  FileTextOutlined,
} from "@ant-design/icons";
import "./dashboard.css";

/* ============================================================
 * Mock 数据
 * ============================================================ */
interface KpiItem {
  key: string;
  icon: string;
  iconGradient: string;
  value: string;
  label: string;
  trend: string;
  trendDirection: "up" | "down" | "neutral";
  accent: string;
}

const kpiData: KpiItem[] = [
  {
    key: "projects",
    icon: "video",
    iconGradient: "linear-gradient(135deg, #6366f1, #4f46e5)",
    value: "12",
    label: "项目总数",
    trend: "↑ 2 本月新增",
    trendDirection: "up",
    accent: "#6366f1",
  },
  {
    key: "assets",
    icon: "appstore",
    iconGradient: "linear-gradient(135deg, #0ea5e9, #0284c7)",
    value: "486",
    label: "素材总数",
    trend: "↑ 38 本月上传",
    trendDirection: "up",
    accent: "#0ea5e9",
  },
  {
    key: "generations",
    icon: "thunderbolt",
    iconGradient: "linear-gradient(135deg, #10b981, #059669)",
    value: "156",
    label: "本月生成数",
    trend: "↑ 23% 较上月",
    trendDirection: "up",
    accent: "#10b981",
  },
  {
    key: "storage",
    icon: "database",
    iconGradient: "linear-gradient(135deg, #f59e0b, #d97706)",
    value: "2.4GB",
    label: "存储空间",
    trend: "已用 24%",
    trendDirection: "neutral",
    accent: "#f59e0b",
  },
];

interface QuickEntry {
  id: string;
  icon: string;
  iconGradient: string;
  title: string;
  description: string;
  path: string;
}

const quickEntries: QuickEntry[] = [
  {
    id: "titles",
    icon: "filetext",
    iconGradient: "linear-gradient(135deg, #6366f1, #4f46e5)",
    title: "标题库",
    description: "24条标题 · 5个分类",
    path: "/app/titles",
  },
  {
    id: "assets",
    icon: "appstore",
    iconGradient: "linear-gradient(135deg, #0ea5e9, #0284c7)",
    title: "素材库",
    description: "486个素材 · 3个素材库",
    path: "/app/assets",
  },
  {
    id: "generate",
    icon: "thunderbolt",
    iconGradient: "linear-gradient(135deg, #10b981, #059669)",
    title: "一键生成",
    description: "开始创作新视频",
    path: "/app/generate",
  },
  {
    id: "products",
    icon: "video",
    iconGradient: "linear-gradient(135deg, #f59e0b, #d97706)",
    title: "成片库",
    description: "89个成片 · 3个待复核",
    path: "/app/products",
  },
];

type TaskStatus = "completed" | "processing" | "pending" | "failed";

interface RecentTask {
  id: string;
  name: string;
  type: string;
  template: string;
  status: TaskStatus;
  date: string;
  duration?: string;
}

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

const recentTasks: RecentTask[] = [
  {
    id: "t-1",
    name: "产品介绍视频_春季促销",
    type: "视频生成",
    template: "商品展示模板",
    status: "completed",
    date: "2026-07-01 09:30",
    duration: "2分18秒",
  },
  {
    id: "t-2",
    name: "品牌宣传片_终版",
    type: "视频生成",
    template: "品牌宣传模板",
    status: "processing",
    date: "2026-07-01 10:15",
  },
  {
    id: "t-3",
    name: "用户评价合集",
    type: "视频生成",
    template: "评价展示模板",
    status: "completed",
    date: "2026-06-30 16:42",
    duration: "1分45秒",
  },
  {
    id: "t-4",
    name: "新品发布预告",
    type: "视频生成",
    template: "新品预告模板",
    status: "pending",
    date: "2026-06-30 14:20",
  },
  {
    id: "t-5",
    name: "活动回顾_618大促",
    type: "视频生成",
    template: "活动回顾模板",
    status: "failed",
    date: "2026-06-29 11:05",
  },
];

interface ChartItem {
  label: string;
  value: number;
}

const weeklyData: ChartItem[] = [
  { label: "周一", value: 18 },
  { label: "周二", value: 25 },
  { label: "周三", value: 32 },
  { label: "周四", value: 28 },
  { label: "周五", value: 42 },
  { label: "周六", value: 15 },
  { label: "周日", value: 8 },
];

interface Announcement {
  id: string;
  tag: "update" | "notice" | "activity";
  tagLabel: string;
  title: string;
  date: string;
}

const announcements: Announcement[] = [
  {
    id: "a-1",
    tag: "update",
    tagLabel: "更新",
    title: "系统已升级至 v2.0，新增批量生成功能",
    date: "2026-07-01",
  },
  {
    id: "a-2",
    tag: "activity",
    tagLabel: "活动",
    title: "7月创作挑战赛已开启，参与赢积分奖励",
    date: "2026-06-28",
  },
  {
    id: "a-3",
    tag: "notice",
    tagLabel: "公告",
    title: "7月3日凌晨 2:00-4:00 系统维护通知",
    date: "2026-06-25",
  },
];

/* ============================================================
 * 工具函数
 * ============================================================ */
const getGreeting = () => {
  const hour = new Date().getHours();
  if (hour < 6) return "夜深了";
  if (hour < 12) return "早上好";
  if (hour < 14) return "中午好";
  if (hour < 18) return "下午好";
  return "晚上好";
};

const formatDate = () => {
  const d = new Date();
  const weekDays = ["日", "一", "二", "三", "四", "五", "六"];
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 星期${weekDays[d.getDay()]}`;
};

/** 图标名称 → Ant Design 组件映射 */
const iconMap: Record<string, React.ReactNode> = {
  video: <VideoCameraOutlined />,
  appstore: <AppstoreOutlined />,
  thunderbolt: <ThunderboltOutlined />,
  database: <DatabaseOutlined />,
  filetext: <FileTextOutlined />,
};

/* ============================================================
 * 组件
 * ============================================================ */
const Dashboard: React.FC = () => {
  const navigate = useNavigate();

  const maxChart = Math.max(...weeklyData.map((d) => d.value));

  return (
    <div className="xx-dashboard-page">
      {/* ── 欢迎头部 ─────────────────────────────────────────── */}
      <div className="xx-dashboard-welcome">
        <h2>{getGreeting()}，创作者</h2>
        <p>{formatDate()} — 欢迎回到小小剪辑控制台</p>
      </div>

      {/* ── KPI 卡片网格 ─────────────────────────────────────── */}
      <div className="xx-kpi-grid">
        {kpiData.map((item) => (
          <div
            key={item.key}
            className="xx-kpi-card"
            style={{ "--kpi-accent": item.accent } as React.CSSProperties}
          >
            <div
              className="xx-kpi-icon"
              style={{ background: item.iconGradient }}
            >
              {iconMap[item.icon] ?? item.icon}
            </div>
            <div className="xx-kpi-value">{item.value}</div>
            <div className="xx-kpi-label">{item.label}</div>
            <span
              className={`xx-kpi-trend xx-kpi-trend--${item.trendDirection}`}
            >
              {item.trend}
            </span>
          </div>
        ))}
      </div>

      {/* ── 主内容区：左侧任务+图表 / 右侧公告 ──────────────── */}
      <div className="xx-dashboard-main">
        {/* 左列 */}
        <div className="xx-dashboard-left-col">
          {/* 最近任务 */}
          <div className="xx-dashboard-section">
            <div className="xx-dashboard-section-header">
              <h3>最近任务</h3>
              <button onClick={() => navigate("/app/history")}>查看全部</button>
            </div>
            <div className="xx-task-list">
              {recentTasks.map((task) => (
                <div key={task.id} className="xx-task-item">
                  <div className="xx-task-info">
                    <h4>{task.name}</h4>
                    <span>
                      {task.type} · 模板：{task.template}
                    </span>
                  </div>
                  <Tag
                    variant={
                      task.status === "completed"
                        ? "success"
                        : task.status === "processing"
                          ? "info"
                          : task.status === "failed"
                            ? "error"
                            : "warning"
                    }
                  >
                    {statusLabel[task.status]}
                  </Tag>
                  <div className="xx-task-time">
                    <span>{task.date}</span>
                    {task.status === "completed"
                      ? `耗时 ${task.duration}`
                      : task.status === "processing"
                        ? "生成中..."
                        : task.status === "failed"
                          ? "请重试"
                          : "等待中"}
                  </div>
                  <div className="xx-task-action">
                    <Button
                      buttonType="ghost"
                      buttonSize="sm"
                      onClick={() => navigate("/app/history")}
                    >
                      查看
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 使用统计图表 */}
          <div className="xx-dashboard-section">
            <div className="xx-dashboard-section-header">
              <h3>本周生成趋势</h3>
              <span className="xx-chart-total">
                共 {weeklyData.reduce((s, d) => s + d.value, 0)} 次
              </span>
            </div>
            <div className="xx-chart-container">
              <div className="xx-chart-bars">
                {weeklyData.map((d, i) => (
                  <div key={i} className="xx-chart-bar-wrapper">
                    <div
                      className="xx-chart-bar"
                      style={{
                        height: `${(d.value / maxChart) * 100}%`,
                      }}
                    >
                      <span className="xx-chart-bar-value">{d.value}</span>
                    </div>
                  </div>
                ))}
              </div>
              <div className="xx-chart-labels">
                {weeklyData.map((d, i) => (
                  <div key={i} className="xx-chart-label">
                    {d.label}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* 右列 — 公告 + 存储用量 */}
        <div className="xx-dashboard-section xx-dashboard-section--start">
          <div className="xx-dashboard-section-header">
            <h3>系统公告</h3>
          </div>
          <div className="xx-announcement-list">
            {announcements.map((a) => (
              <div key={a.id} className="xx-announcement-item">
                <span
                  className={`xx-announcement-tag xx-announcement-tag--${a.tag}`}
                >
                  {a.tagLabel}
                </span>
                <div className="xx-announcement-content">
                  <h4>{a.title}</h4>
                  <time>{a.date}</time>
                </div>
              </div>
            ))}
          </div>

          {/* 存储用量 */}
          <div className="xx-storage-section">
            <div className="xx-storage-section-title">存储用量</div>
            <div className="xx-storage-bar">
              <div className="xx-storage-bar-track">
                <div className="xx-storage-bar-fill" style={{ width: "24%" }} />
              </div>
              <div className="xx-storage-bar-label">
                <span>2.4 GB 已用</span>
                <span>10 GB 总量</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ── 快速入口 ─────────────────────────────────────────── */}
      <div className="xx-quick-entry-section">
        <div className="xx-quick-entry-header">
          <h3 className="xx-quick-entry-title">快速入口</h3>
        </div>
        <div className="xx-quick-grid">
          {quickEntries.map((entry) => (
            <div
              key={entry.id}
              className="xx-quick-card"
              onClick={() => navigate(entry.path)}
            >
              <div
                className="xx-quick-card-icon"
                style={{ background: entry.iconGradient }}
              >
                {iconMap[entry.icon] ?? entry.icon}
              </div>
              <h3>{entry.title}</h3>
              <p>{entry.description}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
