import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { materialDark } from "react-syntax-highlighter/dist/esm/styles/prism";
import { useState, useMemo } from "react";
import "./markdown.less";

interface MarkdownViewerProps {
  content: string;
  renderCode?: (language: string, code: string) => React.ReactNode | undefined;
  codeFooter?: (language: string, code: string) => React.ReactNode | undefined;
}

const CodeHeader: React.FC<{
  language: string;
  onCopy: () => void;
  copied: boolean;
}> = ({ language, onCopy, copied }) => (
  <div
    className="flex justify-between items-center text-white"
    style={{ background: "#afadad", padding: "3px 4px" }}
  >
    <div className="flex items-center">
      <span className="text-xs text-#fff">{language}</span>
    </div>

    <div>
      <span className="cursor-pointer text-xs" onClick={onCopy}>
        {copied ? "已复制!" : "复制代码"}
      </span>
    </div>
  </div>
);

const MarkdownViewer: React.FC<MarkdownViewerProps> = ({ content, renderCode, codeFooter }) => {
  const [copiedIndex, setCopiedIndex] = useState<number | null>(null);

  const filterContent = useMemo(() => {
    return content
      .replaceAll("<think>", `<div class="think"><div class="think-title"><i class="iconfont icon-sikao" style="color: #df9e20;"></i> <span>思考过程</span></div>`)
      .replaceAll("</think>", "</div>");
  }, [content]);

  const handleCopy = (code: string, index: number) => {
    navigator.clipboard.writeText(code);
    setCopiedIndex(index);
    setTimeout(() => setCopiedIndex(null), 2000);
  };

  return (
    <ReactMarkdown
      className="markdown-body"
      remarkPlugins={[remarkGfm]}
      rehypePlugins={[rehypeRaw]}
      components={{
        code({ node, className, children, ...props }) {
          const match = /language-(\w+)/.exec(className || "");
          const code = String(children).replace(/\n$/, "");
          const language = match ? match[1] : "";
          const customRender = renderCode?.(language, code);
          if (customRender) {
            return customRender;
          }
          if (match) {
            return (
              <div className="rounded-md overflow-hidden mb-4">
                <CodeHeader
                  language={language}
                  onCopy={() =>
                    handleCopy(code, node?.position?.start.line ?? 0)
                  }
                  copied={copiedIndex === node?.position?.start.line}
                />
                <div className="max-w-full overflow-x-auto">
                  <SyntaxHighlighter
                    style={materialDark}
                    language={language}
                    PreTag="div"
                    {...props}
                    customStyle={{
                      margin: 0,
                      borderTopLeftRadius: 0,
                      borderTopRightRadius: 0,
                    }}
                  >
                    {code}
                  </SyntaxHighlighter>
                </div>
                { codeFooter?.(language, code)}
              </div>
            );
          }
          return (
            <code className={className} {...props}>
              {children}
            </code>
          );
        },
      }}
    >
      {filterContent}
    </ReactMarkdown>
  );
};

export default MarkdownViewer;
