/**
 * 模板库页面（升级版）— V21 设计系统
 * 任务 2.13：模板类型分类展示、模板预览功能、创建 EditPlan 入口
 *
 * - 按 EditTemplate 类型分组展示
 * - 缩略图 + 预览弹窗
 * - 创建 EditPlan 入口 UI
 * - 使用 useQuery 对接后端真实 API（api/templates.ts, api/editPlans.ts）
 */
import React, { useState, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui";
import {
  LoadingOutlined,
  ExclamationCircleOutlined,
  InboxOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import {
  getTemplates,
  toggleFavoriteTemplate,
  type TemplateItem,
} from "@/api/templates";
import { createEditPlan } from "@/api/editPlans";
import "./templates.css";

/* ============================================================
 * 类型定义（对齐后端 EditTemplate / EditPlan / TemplateClipConfig）
 * ============================================================ */

/** 模板片段配置 */
interface TemplateClipConfig {
  id: string;
  order: number;
  clipType: string;
  description: string;
  duration: number; // 秒
}

/** 模板类型 */
type EditTemplateType = "口播" | "种草" | "产品" | "品牌" | "混剪" | "Vlog";

/** 模板数据（UI 层，映射自后端 TemplateItem） */
interface EditTemplate {
  id: string;
  name: string;
  type: EditTemplateType;
  description: string;
  usageCount: number;
  isFavorite: boolean;
  thumbnailGradient: string;
  scriptContent: string;
  clipConfigs: TemplateClipConfig[];
  recommendedDuration: number; // 秒
  tags: string[];
}

/* ============================================================
 * 映射：后端 TemplateItem → 前端 EditTemplate
 * ============================================================ */

/** 根据 category 推断模板类型 */
const inferTemplateType = (category: string): EditTemplateType => {
  const map: Record<string, EditTemplateType> = {
    口播: "口播",
    种草: "种草",
    产品: "产品",
    品牌: "品牌",
    混剪: "混剪",
    Vlog: "Vlog",
  };
  return map[category] ?? "口播";
};

/** 根据 category 生成占位渐变色 */
const gradientForCategory = (category: string): string => {
  const gradients: Record<string, string> = {
    口播: "linear-gradient(135deg, #6366f1, #8b5cf6)",
    种草: "linear-gradient(135deg, #10b981, #059669)",
    产品: "linear-gradient(135deg, #0ea5e9, #0284c7)",
    品牌: "linear-gradient(135deg, #f59e0b, #d97706)",
    混剪: "linear-gradient(135deg, #8b5cf6, #6d28d9)",
    Vlog: "linear-gradient(135deg, #ec4899, #db2777)",
  };
  return gradients[category] ?? "linear-gradient(135deg, #6366f1, #8b5cf6)";
};

/** 将后端 TemplateItem 映射为前端 EditTemplate */
const mapTemplateItemToEditTemplate = (item: TemplateItem): EditTemplate => ({
  id: item.id,
  name: item.name,
  type: inferTemplateType(item.category),
  description: item.description ?? "",
  usageCount: 0,
  isFavorite: item.is_favorite ?? false,
  thumbnailGradient: gradientForCategory(item.category),
  scriptContent: "",
  clipConfigs: [],
  recommendedDuration: item.target_duration ?? 0,
  tags: [item.category],
});

/* ============================================================
 * 模板类型配置
 * ============================================================ */

const TEMPLATE_TYPES: Array<{
  type: EditTemplateType | "全部";
  label: string;
  icon: string;
  color: string;
}> = [
  { type: "全部", label: "全部", icon: "📋", color: "#6366f1" },
  { type: "口播", label: "口播", icon: "🎙️", color: "#6366f1" },
  { type: "种草", label: "种草", icon: "🌱", color: "#10b981" },
  { type: "产品", label: "产品", icon: "📦", color: "#0ea5e9" },
  { type: "品牌", label: "品牌", icon: "🏷️", color: "#f59e0b" },
  { type: "混剪", label: "混剪", icon: "🎬", color: "#8b5cf6" },
  { type: "Vlog", label: "Vlog", icon: "📹", color: "#ec4899" },
];

/* ============================================================
 * 辅助函数
 * ============================================================ */

/** 获取类型对应颜色 */
const getTypeColor = (type: EditTemplateType): string => {
  const found = TEMPLATE_TYPES.find((t) => t.type === type);
  return found?.color ?? "#6366f1";
};

/** 获取片段类型标签 */
const getClipTypeLabel = (clipType: string): string => clipType;

/** 获取片段类型颜色 */
const getClipTypeColor = (clipType: string): string => {
  const colorMap: Record<string, string> = {
    开场: "#6366f1",
    产品展示: "#0ea5e9",
    卖点讲解: "#10b981",
    结尾: "#f59e0b",
    场景引入: "#8b5cf6",
    产品体验: "#ec4899",
    效果对比: "#14b8a6",
    总结推荐: "#f59e0b",
    悬念开场: "#6366f1",
    产品全景: "#0ea5e9",
    功能演示: "#10b981",
    技术规格: "#64748b",
    品牌起源: "#f59e0b",
    发展历程: "#0ea5e9",
    核心理念: "#8b5cf6",
    未来展望: "#10b981",
    知识点1: "#6366f1",
    知识点2: "#8b5cf6",
    痛点: "#ef4444",
    产品引入: "#10b981",
    使用展示: "#0ea5e9",
    效果: "#f59e0b",
    产品亮相: "#6366f1",
    外观对比: "#0ea5e9",
    性能测试: "#10b981",
    总结: "#f59e0b",
    悬念: "#6366f1",
    亮点: "#10b981",
    福利: "#f59e0b",
    引导: "#0ea5e9",
    高能开场: "#ef4444",
    过渡: "#64748b",
    高潮: "#ec4899",
    早安: "#f59e0b",
    出门: "#10b981",
    日常: "#0ea5e9",
    晚安: "#8b5cf6",
  };
  return colorMap[clipType] ?? "#6366f1";
};

/** 格式化时长 */
const formatDuration = (seconds: number): string => {
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  if (m === 0) return `${s}秒`;
  return `${m}分${s > 0 ? `${s}秒` : ""}`;
};

/* ============================================================
 * 预览弹窗组件
 * ============================================================ */

interface TemplatePreviewModalProps {
  template: EditTemplate;
  isFavorite: boolean;
  onClose: () => void;
  onToggleFavorite: (id: string) => void;
  onUse: (template: EditTemplate) => void;
}

const TemplatePreviewModal: React.FC<TemplatePreviewModalProps> = ({
  template,
  isFavorite,
  onClose,
  onToggleFavorite,
  onUse,
}) => {
  const totalDuration = template.clipConfigs.reduce(
    (sum, c) => sum + c.duration,
    0,
  );

  return (
    <div className="xx-template-modal-overlay" onClick={onClose}>
      <div className="xx-template-modal" onClick={(e) => e.stopPropagation()}>
        {/* 关闭按钮 */}
        <button
          className="xx-template-modal-close"
          onClick={onClose}
          title="关闭"
        >
          ✕
        </button>

        {/* 预览区域 */}
        <div
          className="xx-template-modal-preview"
          style={{ background: template.thumbnailGradient }}
        >
          <div className="xx-template-modal-preview-content">
            <span className="xx-template-preview-icon">
              {TEMPLATE_TYPES.find((t) => t.type === template.type)?.icon ??
                "📋"}
            </span>
            <span className="xx-template-preview-title">{template.name}</span>
          </div>
        </div>

        {/* 内容区域 */}
        <div className="xx-template-modal-content">
          {/* 标题行 */}
          <div className="xx-template-modal-title-row">
            <h3>{template.name}</h3>
            <span
              className="xx-template-modal-type-badge"
              style={{
                color: getTypeColor(template.type),
                background: `${getTypeColor(template.type)}18`,
              }}
            >
              {TEMPLATE_TYPES.find((t) => t.type === template.type)?.icon}{" "}
              {template.type}
            </span>
          </div>

          {/* 描述 */}
          <p className="xx-template-modal-desc">{template.description}</p>

          {/* 标签 */}
          <div className="xx-template-modal-tags">
            {template.tags.map((tag) => (
              <span key={tag} className="xx-template-modal-tag">
                #{tag}
              </span>
            ))}
          </div>

          {/* 脚本内容 */}
          {template.scriptContent && (
            <div className="xx-template-modal-section">
              <h4>📝 脚本内容</h4>
              <pre className="xx-template-modal-script">
                {template.scriptContent}
              </pre>
            </div>
          )}

          {/* 视频结构 */}
          {template.clipConfigs.length > 0 && (
            <div className="xx-template-modal-section">
              <h4>🎬 视频结构</h4>
              <div className="xx-template-modal-clip-list">
                {template.clipConfigs
                  .sort((a, b) => a.order - b.order)
                  .map((clip) => (
                    <div key={clip.id} className="xx-template-modal-clip-item">
                      <span
                        className="xx-template-modal-clip-badge"
                        style={{
                          color: getClipTypeColor(clip.clipType),
                          background: `${getClipTypeColor(clip.clipType)}18`,
                        }}
                      >
                        {getClipTypeLabel(clip.clipType)}
                      </span>
                      <span className="xx-template-modal-clip-desc">
                        {clip.description}
                      </span>
                      <span className="xx-template-modal-clip-duration">
                        {clip.duration}秒
                      </span>
                    </div>
                  ))}
              </div>
              <div className="xx-template-modal-total-duration">
                总时长：{formatDuration(totalDuration)}
                {template.recommendedDuration !== totalDuration && (
                  <span>
                    {" "}
                    · 推荐时长：{formatDuration(template.recommendedDuration)}
                  </span>
                )}
              </div>
            </div>
          )}

          {/* 统计信息 */}
          <div className="xx-template-modal-stats">
            <span>已使用 {template.usageCount} 次</span>
            <button
              className={`xx-template-modal-fav-btn${isFavorite ? " is-favorite" : ""}`}
              onClick={() => onToggleFavorite(template.id)}
            >
              {isFavorite ? "★ 已收藏" : "☆ 收藏"}
            </button>
          </div>

          {/* 操作按钮 */}
          <div className="xx-template-modal-actions">
            <Button buttonType="ghost" buttonSize="md" onClick={onClose}>
              取消
            </Button>
            <Button
              buttonType="primary"
              buttonSize="md"
              onClick={() => onUse(template)}
            >
              使用此模板
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

/* ============================================================
 * 模板卡片组件
 * ============================================================ */

interface TemplateCardProps {
  template: EditTemplate;
  isFavorite: boolean;
  onPreview: (template: EditTemplate) => void;
  onToggleFavorite: (id: string, e: React.MouseEvent) => void;
  onUse: (template: EditTemplate) => void;
}

const TemplateCard: React.FC<TemplateCardProps> = ({
  template,
  isFavorite,
  onPreview,
  onToggleFavorite,
  onUse,
}) => {
  return (
    <div className="xx-template-card" onClick={() => onPreview(template)}>
      {/* 缩略图 */}
      <div className="xx-template-thumb">
        <div
          className="xx-template-thumb-bg"
          style={{ background: template.thumbnailGradient }}
        >
          {(template.description ?? "").slice(0, 80)}...
        </div>
        <div className="xx-template-thumb-overlay" />
        <div className="xx-template-thumb-name">{template.name}</div>
        <div className="xx-template-preview-hint">点击预览</div>
        <button
          className={`xx-template-fav-btn${isFavorite ? " is-favorite" : ""}`}
          onClick={(e) => onToggleFavorite(template.id, e)}
          title={isFavorite ? "取消收藏" : "收藏"}
        >
          {isFavorite ? "★" : "☆"}
        </button>
      </div>

      {/* 信息区 */}
      <div className="xx-template-info">
        <div className="xx-template-info-top">
          <span
            className="xx-template-category-pill"
            style={{
              color: getTypeColor(template.type),
              background: `${getTypeColor(template.type)}18`,
            }}
          >
            {template.type}
          </span>
        </div>
        <p className="xx-template-desc">{template.description ?? ""}</p>
        <div className="xx-template-meta">
          <span className="xx-template-usage">
            已使用 {template.usageCount} 次
          </span>
          <button
            className="xx-template-use-btn"
            onClick={(e) => {
              e.stopPropagation();
              onUse(template);
            }}
          >
            使用此模板
          </button>
        </div>
      </div>
    </div>
  );
};

/* ============================================================
 * 主组件
 * ============================================================ */

const TemplateLibrary: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [searchText, setSearchText] = useState("");
  const [activeType, setActiveType] = useState<EditTemplateType | "全部">(
    "全部",
  );
  const [previewTemplate, setPreviewTemplate] = useState<EditTemplate | null>(
    null,
  );

  // ── 获取模板列表 ──
  const {
    data: apiTemplates = [],
    isLoading,
    isError,
    error,
  } = useQuery<TemplateItem[], Error>({
    queryKey: ["templates"],
    queryFn: getTemplates,
    staleTime: 60_000,
  });

  // 将后端数据映射为前端 EditTemplate
  const templates = useMemo(
    () => apiTemplates.map(mapTemplateItemToEditTemplate),
    [apiTemplates],
  );

  // ── 收藏 mutation ──
  const favMutation = useMutation({
    mutationFn: toggleFavoriteTemplate,
    onSuccess: (_data, templateId) => {
      // 乐观更新：刷新模板列表
      queryClient.invalidateQueries({ queryKey: ["templates"] });
      // 同时更新当前预览（如果有）
      if (previewTemplate && previewTemplate.id === templateId) {
        setPreviewTemplate((prev) =>
          prev ? { ...prev, isFavorite: !prev.isFavorite } : prev,
        );
      }
    },
  });

  // ── 创建 EditPlan mutation ──
  const createPlanMutation = useMutation({
    mutationFn: (params: { template_id: string; name: string }) =>
      createEditPlan(params),
  });

  /** 切换收藏 */
  const toggleFavorite = (id: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    favMutation.mutate(id);
  };

  /** 过滤模板 */
  const filtered = useMemo(() => {
    return templates.filter((t) => {
      const matchSearch =
        !searchText ||
        t.name.toLowerCase().includes(searchText.toLowerCase()) ||
        (t.description ?? "")
          .toLowerCase()
          .includes(searchText.toLowerCase()) ||
        t.tags.some((tag) =>
          tag.toLowerCase().includes(searchText.toLowerCase()),
        );
      const matchType = activeType === "全部" || t.type === activeType;
      return matchSearch && matchType;
    });
  }, [searchText, activeType, templates]);

  /** 按类型分组 */
  const groupedTemplates = useMemo(() => {
    const groups: Record<string, EditTemplate[]> = {};
    for (const tpl of filtered) {
      if (!groups[tpl.type]) groups[tpl.type] = [];
      groups[tpl.type].push(tpl);
    }
    return groups;
  }, [filtered]);

  /** 使用模板 → 创建 EditPlan */
  const handleUseTemplate = async (template: EditTemplate) => {
    try {
      await createPlanMutation.mutateAsync({
        template_id: template.id,
        name: `基于「${template.name}」的剪辑计划`,
      });
      navigate("/app/editing-planner");
    } catch (err) {
      console.error("[TemplateLibrary] createEditPlan failed:", err);
    }
  };

  // ── Loading 状态 ──
  if (isLoading) {
    return (
      <div className="xx-templates-page">
        <div className="xx-templates-empty">
          <div className="xx-templates-empty-icon">
            <LoadingOutlined />
          </div>
          <h3>加载模板中...</h3>
        </div>
      </div>
    );
  }

  // ── Error 状态 ──
  if (isError) {
    return (
      <div className="xx-templates-page">
        <div className="xx-templates-empty">
          <div className="xx-templates-empty-icon">
            <ExclamationCircleOutlined />
          </div>
          <h3>加载失败</h3>
          <p>{error?.message || "网络异常，请稍后重试"}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="xx-templates-page">
      {/* ── 页面头部 ──────────────────────────────────────────── */}
      <div className="xx-templates-header">
        <div className="xx-templates-header-text">
          <h2>模板库</h2>
          <p>选择模板快速创建剪辑计划，支持自定义修改</p>
        </div>
        <Button
          buttonType="primary"
          buttonSize="md"
          onClick={() => navigate("/app/editing-planner")}
        >
          + 创建模板
        </Button>
      </div>

      {/* ── 工具栏：搜索 + 类型按钮组 ─────────────────────────── */}
      <div className="xx-templates-toolbar">
        <div className="xx-templates-search">
          <span className="xx-templates-search-icon">
            <SearchOutlined />
          </span>
          <input
            className="xx-templates-search-input"
            type="text"
            placeholder="搜索模板名称、描述或标签..."
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
          />
        </div>
        <div className="xx-templates-categories">
          {TEMPLATE_TYPES.map((cat) => (
            <button
              key={cat.type}
              className={`xx-templates-cat-btn${activeType === cat.type ? " active" : ""}`}
              onClick={() => setActiveType(cat.type)}
            >
              <span className="xx-templates-cat-icon">{cat.icon}</span>
              {cat.label}
            </button>
          ))}
        </div>
      </div>

      {/* ── 模板展示区 ────────────────────────────────────────── */}
      {filtered.length === 0 ? (
        <div className="xx-templates-empty">
          <div className="xx-templates-empty-icon">
            <InboxOutlined />
          </div>
          <h3>
            {searchText || activeType !== "全部"
              ? "未找到匹配的模板"
              : "暂无模板"}
          </h3>
          <p>
            {searchText || activeType !== "全部"
              ? "试试调整搜索条件或切换类型"
              : "点击上方「创建模板」开始创作"}
          </p>
        </div>
      ) : activeType === "全部" ? (
        /* 全部类型 → 按类型分组展示 */
        <div className="xx-templates-grouped">
          {Object.entries(groupedTemplates).map(([type, tpls]) => {
            const typeConfig = TEMPLATE_TYPES.find((t) => t.type === type);
            return (
              <div key={type} className="xx-templates-group">
                <div className="xx-templates-group-header">
                  <span className="xx-templates-group-icon">
                    {typeConfig?.icon ?? "📋"}
                  </span>
                  <h3>{type}</h3>
                  <span className="xx-templates-group-count">
                    {tpls.length} 个模板
                  </span>
                </div>
                <div className="xx-templates-grid">
                  {tpls.map((tpl) => (
                    <TemplateCard
                      key={tpl.id}
                      template={tpl}
                      isFavorite={tpl.isFavorite}
                      onPreview={setPreviewTemplate}
                      onToggleFavorite={toggleFavorite}
                      onUse={handleUseTemplate}
                    />
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        /* 单类型 → 平铺网格 */
        <div className="xx-templates-grid">
          {filtered.map((tpl) => (
            <TemplateCard
              key={tpl.id}
              template={tpl}
              isFavorite={tpl.isFavorite}
              onPreview={setPreviewTemplate}
              onToggleFavorite={toggleFavorite}
              onUse={handleUseTemplate}
            />
          ))}
        </div>
      )}

      {/* ── 预览弹窗 ──────────────────────────────────────────── */}
      {previewTemplate && (
        <TemplatePreviewModal
          template={previewTemplate}
          isFavorite={previewTemplate.isFavorite}
          onClose={() => setPreviewTemplate(null)}
          onToggleFavorite={toggleFavorite}
          onUse={handleUseTemplate}
        />
      )}
    </div>
  );
};

export default TemplateLibrary;
