/**
 * 我的模板页面
 * 卡片视图展示用户已保存的剪辑模板
 * 支持搜索、分类筛选、编辑/复制/删除/使用模板生成
 */
import React, { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Typography,
  Card,
  Input,
  Select,
  Tag,
  Button,
  Space,
  Empty,
  Spin,
  Tooltip,
  message,
  Popconfirm,
  Row,
  Col,
} from "antd";
import {
  SearchOutlined,
  EditOutlined,
  CopyOutlined,
  DeleteOutlined,
  VideoCameraOutlined,
  AppstoreOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import {
  getEditingTemplates,
  getTemplateCategories,
  deleteEditingTemplate,
  createEditingTemplate,
  MODE_LABELS,
  MODE_COLORS,
  type EditingTemplate,
  type TemplateMode,
} from "@/api/editingPlanner";
import "./MyTemplates.css";

const { Title, Text } = Typography;

const MyTemplates: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  const [searchText, setSearchText] = useState("");
  const [filterCategory, setFilterCategory] = useState("");

  /* ── 数据查询 ── */
  const { data: templates = [], isLoading } = useQuery({
    queryKey: ["editing-templates", filterCategory, searchText],
    queryFn: () =>
      getEditingTemplates({
        category: filterCategory || undefined,
        tag: searchText || undefined,
      }),
  });

  const { data: categories = [] } = useQuery({
    queryKey: ["template-categories"],
    queryFn: getTemplateCategories,
  });

  /* ── Mutations ── */
  const deleteMutation = useMutation({
    mutationFn: deleteEditingTemplate,
    onSuccess: () => {
      message.success("模板已删除");
      queryClient.invalidateQueries({ queryKey: ["editing-templates"] });
    },
    onError: (err: unknown) => {
      if (!(err as { __msgShown?: boolean })?.__msgShown)
        message.error("删除失败");
    },
  });

  const copyMutation = useMutation({
    mutationFn: (tpl: EditingTemplate) =>
      createEditingTemplate({
        name: `${tpl.name}（副本）`,
        mode: tpl.mode,
        category: tpl.category,
        tags: tpl.tags,
        title_config: tpl.title_config,
        subtitle_config: tpl.subtitle_config,
        bgm_config: tpl.bgm_config,
        estimated_duration:
          tpl.estimated_duration ??
          Math.round(
            tpl.segments.reduce(
              (s, seg) => s + (seg.duration_min + seg.duration_max) / 2,
              0,
            ),
          ),
        segments: tpl.segments.map(({ id: _id, ...rest }) => rest),
      }),
    onSuccess: () => {
      message.success("模板已复制");
      queryClient.invalidateQueries({ queryKey: ["editing-templates"] });
    },
    onError: (err: unknown) => {
      if (!(err as { __msgShown?: boolean })?.__msgShown)
        message.error("复制失败");
    },
  });

  /* ── 操作 ── */
  const handleEdit = (tpl: EditingTemplate) => {
    navigate(`/editing-planner?template=${tpl.id}`);
  };

  const handleGenerate = (tpl: EditingTemplate) => {
    navigate(`/editing-planner?template=${tpl.id}&generate=1`);
  };

  const handleCopy = (tpl: EditingTemplate) => {
    copyMutation.mutate(tpl);
  };

  const handleDelete = (id: string) => {
    deleteMutation.mutate(id);
  };

  return (
    <div className="mt-page">
      {/* 页面头部 */}
      <div className="mt-head">
        <div>
          <Title level={4} style={{ margin: 0 }}>
            <AppstoreOutlined style={{ marginRight: 8 }} />
            我的模板
          </Title>
          <Text type="secondary">管理你创建的剪辑模板，快速复用生成视频</Text>
        </div>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => navigate("/app/editing-planner")}
        >
          新建模板
        </Button>
      </div>

      {/* 筛选栏 */}
      <div className="mt-filters">
        <Input
          prefix={<SearchOutlined />}
          placeholder="搜索模板名称或标签..."
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          allowClear
          style={{ width: 280 }}
        />
        <Select
          placeholder="按分类筛选"
          value={filterCategory || undefined}
          onChange={(v) => setFilterCategory(v || "")}
          allowClear
          style={{ width: 160 }}
          options={categories.map((c) => ({ value: c.name, label: c.name }))}
        />
      </div>

      {/* 模板卡片列表 */}
      <div className="mt-content">
        {isLoading ? (
          <div style={{ textAlign: "center", padding: 80 }}>
            <Spin size="large" />
          </div>
        ) : templates.length === 0 ? (
          <Empty
            description="还没有模板，点击右上角「新建模板」开始创建"
            style={{ padding: 80 }}
          >
            <Button
              type="primary"
              onClick={() => navigate("/app/editing-planner")}
            >
              新建模板
            </Button>
          </Empty>
        ) : (
          <Row gutter={[16, 16]}>
            {templates.map((tpl) => (
              <Col key={tpl.id} xs={24} sm={12} md={8} lg={6}>
                <Card
                  className="mt-card"
                  hoverable
                  actions={[
                    <Tooltip title="编辑" key="edit">
                      <EditOutlined onClick={() => handleEdit(tpl)} />
                    </Tooltip>,
                    <Tooltip title="复制" key="copy">
                      <CopyOutlined onClick={() => handleCopy(tpl)} />
                    </Tooltip>,
                    <Tooltip title="使用模板生成" key="generate">
                      <VideoCameraOutlined
                        onClick={() => handleGenerate(tpl)}
                      />
                    </Tooltip>,
                    <Popconfirm
                      key="delete"
                      title="确定删除此模板？"
                      onConfirm={() => handleDelete(tpl.id)}
                      okText="删除"
                      cancelText="取消"
                    >
                      <Tooltip title="删除">
                        <DeleteOutlined style={{ color: "#ff4d4f" }} />
                      </Tooltip>
                    </Popconfirm>,
                  ]}
                >
                  <div className="mt-card-head">
                    <Text strong ellipsis style={{ fontSize: 15 }}>
                      {tpl.name}
                    </Text>
                    <Tag
                      color={MODE_COLORS[tpl.mode as TemplateMode] || "default"}
                    >
                      {MODE_LABELS[tpl.mode as TemplateMode] || tpl.mode}
                    </Tag>
                    <Tag color="green">用户自制</Tag>
                  </div>

                  <div className="mt-card-meta">
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {tpl.segments.length} 片段 · 预估 ~
                      {tpl.estimated_duration}s
                    </Text>
                    {tpl.category && (
                      <Tag style={{ fontSize: 11, marginTop: 4 }}>
                        {tpl.category}
                      </Tag>
                    )}
                  </div>

                  {tpl.tags.length > 0 && (
                    <div className="mt-card-tags">
                      {tpl.tags.map((tag) => (
                        <Tag key={tag} style={{ fontSize: 11 }}>
                          {tag}
                        </Tag>
                      ))}
                    </div>
                  )}

                  <div className="mt-card-config">
                    <Space size={4} wrap>
                      {tpl.title_config.ai_auto_select && (
                        <Tag color="cyan">AI标题</Tag>
                      )}
                      {tpl.subtitle_config.enabled && (
                        <Tag color="geekblue">字幕</Tag>
                      )}
                      {tpl.bgm_config.enabled && <Tag color="pink">BGM</Tag>}
                    </Space>
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        )}
      </div>
    </div>
  );
};

export default MyTemplates;
