import React, { useState, useCallback } from "react";
import ReactMarkdown from "react-markdown";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";
import { CopyToClipboard } from "react-copy-to-clipboard";
import "katex/dist/katex.min.css";

// 复制图标
const CopyIcon = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
    <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
  </svg>
);

// 代码块组件
const CodeBlock = ({ node, inline, className, children, ...props }) => {
  const [copied, setCopied] = useState(false);
  const match = /language-(\w+)/.exec(className || "");
  const codeContent = String(children).replace(/\n$/, "");

  // 行内代码
  if (inline) {
    return (
      <code className="inline-code" {...props}>
        {children}
      </code>
    );
  }

  const handleCopy = () => {
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="code-block-wrapper">
      <div className="code-block-header">
        <span className="code-language">{match?.[1] || "text"}</span>
        <CopyToClipboard text={codeContent} onCopy={handleCopy}>
          <button className="copy-button" title="复制代码">
            {copied ? "✓ 已复制" : <><CopyIcon /> 复制</>}
          </button>
        </CopyToClipboard>
      </div>
      <SyntaxHighlighter
        style={oneDark}
        language={match?.[1] || "text"}
        PreTag="div"
        showLineNumbers
        customStyle={{
          margin: 0,
          borderRadius: "0 0 8px 8px",
          fontSize: "0.85rem",
          lineHeight: "1.5"
        }}
        {...props}
      >
        {codeContent}
      </SyntaxHighlighter>
    </div>
  );
};

// Markdown 渲染组件
const MarkdownRenderer = ({ content, className = "" }) => {
  if (!content) return null;

  return (
    <div className={`markdown-content ${className}`}>
      <ReactMarkdown
        remarkPlugins={[remarkMath]}
        rehypePlugins={[rehypeKatex]}
        components={{
          code: CodeBlock,
          // 自定义段落样式
          p: ({ children }) => <p className="md-paragraph">{children}</p>,
          // 自定义列表样式
          ul: ({ children }) => <ul className="md-list">{children}</ul>,
          ol: ({ children }) => <ol className="md-list md-list-ordered">{children}</ol>,
          li: ({ children }) => <li className="md-list-item">{children}</li>,
          // 自定义标题样式
          h1: ({ children }) => <h1 className="md-heading md-h1">{children}</h1>,
          h2: ({ children }) => <h2 className="md-heading md-h2">{children}</h2>,
          h3: ({ children }) => <h3 className="md-heading md-h3">{children}</h3>,
          h4: ({ children }) => <h4 className="md-heading md-h4">{children}</h4>,
          // 自定义引用块
          blockquote: ({ children }) => (
            <blockquote className="md-blockquote">{children}</blockquote>
          ),
          // 自定义表格
          table: ({ children }) => <table className="md-table">{children}</table>,
          thead: ({ children }) => <thead className="md-table-head">{children}</thead>,
          tbody: ({ children }) => <tbody className="md-table-body">{children}</tbody>,
          tr: ({ children }) => <tr className="md-table-row">{children}</tr>,
          th: ({ children }) => <th className="md-table-cell md-table-header">{children}</th>,
          td: ({ children }) => <td className="md-table-cell">{children}</td>,
          // 自定义链接
          a: ({ href, children }) => (
            <a href={href} target="_blank" rel="noopener noreferrer" className="md-link">
              {children}
            </a>
          ),
          // 自定义图片
          img: ({ src, alt }) => (
            <img src={src} alt={alt} className="md-image" />
          ),
          // 自定义分隔线
          hr: () => <hr className="md-divider" />,
        }}
      >
        {content}
      </ReactMarkdown>
    </div>
  );
};

export default MarkdownRenderer;
