import {
  CameraOutlined,
  ClockCircleOutlined,
  ColumnWidthOutlined,
  CustomerServiceOutlined,
  DashboardOutlined,
  DeleteOutlined,
  EditOutlined,
  HighlightOutlined,
  MessageOutlined,
  SwapOutlined,
  ThunderboltOutlined,
  VideoCameraOutlined,
} from "@ant-design/icons";
import type { ReactNode } from "react";
import { useCallback, useEffect, useState } from "react";
import type { WebImageWorkbenchTool, WebViewKey } from "../../types";

interface MorePageProps {
  onSelectView?: (view: WebViewKey) => void;
  onOpenImageTool?: (tool: WebImageWorkbenchTool) => void;
}

type ToolCategory = "image" | "video";
type FilterKey = "all" | ToolCategory | "upcoming";

interface MoreTool {
  id: string;
  title: string;
  text: string;
  icon: ReactNode;
  category: ToolCategory;
  target?: WebViewKey;
  imageTool?: WebImageWorkbenchTool;
  ready: boolean;
  badge?: string;
  featured?: boolean;
}

const tools: MoreTool[] = [
  { id: "workbench", title: "图片工作台", text: "融合、修复、局部增强", icon: <EditOutlined />, category: "image", imageTool: "workbench", ready: true, featured: true },
  { id: "inpaint", title: "局部重绘", text: "遮罩区域重新生成", icon: <HighlightOutlined />, category: "image", imageTool: "inpaint", ready: true },
  { id: "camera", title: "镜头实验室", text: "角度、焦段和机位控制", icon: <CameraOutlined />, category: "image", imageTool: "camera", ready: true },
  { id: "upscale", title: "分辨率提升", text: "图片与视频高清超分", icon: <ColumnWidthOutlined />, category: "image", target: "resolutionUpscale", ready: true },
  { id: "watermarkRemoval", title: "去水印", text: "AI 智能去除图片水印和文字", icon: <DeleteOutlined />, category: "image", target: "watermarkRemoval", ready: true },
  { id: "dialogGenerator", title: "交互式对话框生成器", text: "上传背景图，添加可拖拽编辑的对话框", icon: <MessageOutlined />, category: "image", target: "dialogGenerator", ready: true },
  { id: "subtitleRemoval", title: "字幕去除", text: "AI 智能擦除视频字幕", icon: <DeleteOutlined />, category: "video", target: "subtitleRemoval", ready: true },
  { id: "digitalHuman", title: "数字人", text: "参考人像与音频生成口播视频", icon: <CustomerServiceOutlined />, category: "video", target: "digitalHuman", ready: true, featured: true },
  { id: "characterMix", title: "角色迁移", text: "人物图迁移到参考视频动作", icon: <SwapOutlined />, category: "video", target: "characterMix", ready: true },
  { id: "avatarConsole", title: "数字人控制台", text: "形象、播报、互动与接入配置", icon: <DashboardOutlined />, category: "video", target: "avatarConsole", ready: true },
];

interface FeaturedTool {
  id: string;
  title: string;
  desc: string;
  icon: ReactNode;
  imageTool?: WebImageWorkbenchTool;
  target?: WebViewKey;
  category: ToolCategory;
  gradient: string;
}

const featuredTools: FeaturedTool[] = [
  {
    id: "workbench",
    title: "图片工作台",
    desc: "融合、修复、局部增强 — 一站式图片创作",
    icon: <EditOutlined />,
    imageTool: "workbench",
    category: "image",
    gradient: "linear-gradient(135deg, rgba(99, 102, 241, 0.12), rgba(139, 92, 246, 0.06))",
  },
  {
    id: "digitalHuman",
    title: "数字人",
    desc: "参考人像与音频，一键生成口播视频",
    icon: <CustomerServiceOutlined />,
    target: "digitalHuman",
    category: "video",
    gradient: "linear-gradient(135deg, rgba(13, 148, 136, 0.12), rgba(6, 182, 212, 0.06))",
  },
];

const categoryLabels: Record<ToolCategory, string> = {
  image: "图像创作",
  video: "视频生成",
};

const categoryIcons: Record<ToolCategory, ReactNode> = {
  image: <EditOutlined />,
  video: <VideoCameraOutlined />,
};

const filters: { key: FilterKey; label: string }[] = [
  { key: "all", label: "全部" },
  { key: "image", label: "图像" },
  { key: "video", label: "视频" },
  { key: "upcoming", label: "即将上线" },
];

const RECENT_STORAGE_KEY = "omniai:more-recent-tools";
const MAX_RECENT = 4;

function getRecentToolIds(): string[] {
  try {
    const raw = localStorage.getItem(RECENT_STORAGE_KEY);
    return raw ? JSON.parse(raw) : [];
  } catch { return []; }
}

function pushRecentToolId(id: string) {
  const ids = getRecentToolIds().filter((x) => x !== id);
  ids.unshift(id);
  localStorage.setItem(RECENT_STORAGE_KEY, JSON.stringify(ids.slice(0, MAX_RECENT)));
}

function MorePage({ onSelectView, onOpenImageTool }: MorePageProps) {
  const [filter, setFilter] = useState<FilterKey>("all");
  const [recentIds, setRecentIds] = useState<string[]>(getRecentToolIds);

  useEffect(() => {
    setRecentIds(getRecentToolIds());
  }, []);

  const openTool = useCallback((tool: MoreTool) => {
    if (!tool.ready) return;
    pushRecentToolId(tool.id);
    setRecentIds(getRecentToolIds());
    if (tool.imageTool && onOpenImageTool) {
      onOpenImageTool(tool.imageTool);
      return;
    }
    if (tool.target && onSelectView) {
      onSelectView(tool.target);
    }
  }, [onOpenImageTool, onSelectView]);

  const filteredTools = tools.filter((t) => {
    if (t.featured) return false;
    if (filter === "all") return true;
    if (filter === "upcoming") return !t.ready;
    return t.category === filter;
  });

  const recentTools = recentIds
    .map((id) => tools.find((t) => t.id === id))
    .filter((t): t is MoreTool => Boolean(t) && (t?.ready ?? false));

  const groupedTools = filteredTools.reduce<Record<ToolCategory, MoreTool[]>>((acc, t) => {
    if (!acc[t.category]) acc[t.category] = [];
    acc[t.category].push(t);
    return acc;
  }, {} as Record<ToolCategory, MoreTool[]>);

  return (
    <div className="more-page-v2">
      <header className="more-page-v2__header">
        <h1>工具盒</h1>
        <nav className="more-page-v2__filters">
          {filters.map((f) => (
            <button
              key={f.key}
              type="button"
              className={filter === f.key ? "is-active" : ""}
              onClick={() => setFilter(f.key)}
            >
              {f.label}
            </button>
          ))}
        </nav>
      </header>

      <div className="more-page-v2__scroll">
        {recentTools.length > 0 && filter === "all" && (
          <section className="more-page-v2__section">
            <h2 className="more-page-v2__section-title">
              <ClockCircleOutlined /> 最近使用
            </h2>
            <div className="more-page-v2__recent-row">
              {recentTools.map((tool) => (
                <button
                  key={tool.id}
                  type="button"
                  className="more-card more-card--recent"
                  onClick={() => openTool(tool)}
                >
                  <span className="more-card__icon">{tool.icon}</span>
                  <strong>{tool.title}</strong>
                </button>
              ))}
            </div>
          </section>
        )}

        {filter === "all" && (
          <section className="more-page-v2__section more-page-v2__featured">
            <h2 className="more-page-v2__section-title">
              <ThunderboltOutlined /> 核心工具
            </h2>
            <div className="more-page-v2__featured-grid">
              {featuredTools.map((tool) => (
                <button
                  key={tool.id}
                  type="button"
                  className="more-card more-card--featured"
                  style={{ "--card-gradient": tool.gradient } as React.CSSProperties}
                  onClick={() => {
                    pushRecentToolId(tool.id);
                    setRecentIds(getRecentToolIds());
                    if (tool.imageTool && onOpenImageTool) {
                      onOpenImageTool(tool.imageTool);
                      return;
                    }
                    if (tool.target && onSelectView) {
                      onSelectView(tool.target);
                    }
                  }}
                >
                  <span className="more-card__featured-icon">{tool.icon}</span>
                  <div className="more-card__featured-body">
                    <strong>{tool.title}</strong>
                    <span>{tool.desc}</span>
                    <span className="more-card__cta">开始使用 →</span>
                  </div>
                </button>
              ))}
            </div>
          </section>
        )}

        {(["image", "video", "template"] as ToolCategory[]).map((cat) => {
          const group = groupedTools[cat];
          if (!group || group.length === 0) return null;
          return (
            <section key={cat} className="more-page-v2__section">
              <h2 className="more-page-v2__section-title">
                {categoryIcons[cat]} {categoryLabels[cat]}
              </h2>
              <div className="more-page-v2__grid">
                {group.map((tool) => (
                  <button
                    key={tool.id}
                    type="button"
                    className={`more-card${tool.ready ? " more-card--ready" : " more-card--pending"}`}
                    onClick={() => openTool(tool)}
                    disabled={!tool.ready}
                  >
                    <span className="more-card__icon">{tool.icon}</span>
                    <strong>{tool.title}</strong>
                    <span className="more-card__desc">{tool.text}</span>
                    {tool.badge && <span className="more-card__badge">{tool.badge}</span>}
                  </button>
                ))}
              </div>
            </section>
          );
        })}
      </div>
    </div>
  );
}

export default MorePage;
