import React, { memo, useMemo } from "react";
import ReactMarkdown from "react-markdown";
import styles from "./markdown.module.css";
import CodeBlock from "../codeBlock/codeBlock";
import remarkGfm from "remark-gfm";
import Chip from "../chip/chip";

interface MarkdownBlockProps {
  markdown?: string;
  currentOptimizedFunction?: string;
}

const MarkdownBlock = memo(
  ({ markdown, currentOptimizedFunction }: MarkdownBlockProps) => {
    const components = useMemo(
      () => ({
        table: ({ children, ...props }: any) => {
          return (
            <div className="table-wrapper">
              <table {...props}>{children}</table>
            </div>
          );
        },
        a: ({ href, children, ...props }: any) => {
          const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
            // Only process file:// protocol or local file paths
            const isLocalPath =
              href?.startsWith("file://") ||
              href?.startsWith("/") ||
              !href?.includes("://");

            if (!isLocalPath) {
              return;
            }

            e.preventDefault();

            // Handle absolute vs project-relative paths
            let filePath = href.replace("file://", "");

            // Extract line number if present
            // const match = filePath.match(/(.*):(\d+)(-\d+)?$/)
            // let values = undefined
            // if (match) {
            // 	filePath = match[1]
            // 	values = { line: parseInt(match[2]) }
            // }

            // Add ./ prefix if needed
            if (!filePath.startsWith("/") && !filePath.startsWith("./")) {
              filePath = "./" + filePath;
            }

            // vscode.postMessage({
            // 	type: "openFile",
            // 	text: filePath,
            // 	values,
            // })
          };

          return (
            <a {...props} href={href} onClick={handleClick}>
              {children}
            </a>
          );
        },
        pre: ({ children }: any) => {
          // The structure from react-markdown v9 is: pre > code > text
          const codeEl = children as React.ReactElement;

          if (!codeEl || !codeEl.props) {
            return <pre>{children}</pre>;
          }

          const { className = "", children: codeChildren } = codeEl.props as {
            className?: string;
            children?: React.ReactNode;
          };

          // Get the actual code text
          let codeString = "";
          if (typeof codeChildren === "string") {
            codeString = codeChildren;
          } else if (Array.isArray(codeChildren)) {
            codeString = codeChildren
              .filter((child) => typeof child === "string")
              .join("");
          }

          // Extract language from className
          const match = /language-(\w+)/.exec(className);
          const language = match ? match[1] : "text";
          // Wrap CodeBlock in a div to ensure proper separation
          return (
            <div style={{ margin: "1em 0" }}>
              <CodeBlock source={codeString} language={language!} />
            </div>
          );
        },
        code: ({ children, className, ...props }: any) => {
          const isSingleLineString =
            typeof children === "string" && children.split("\n").length === 1;

          const isFilePath = isSingleLineString && children.endsWith(".py");
          const isTargetFunction =
            isSingleLineString &&
            currentOptimizedFunction &&
            children === currentOptimizedFunction;

          if (isFilePath) {
            return (
              <Chip
                onClick={(e) => e.stopPropagation()}
                style={{ background: "var(--code-block-bg" }}
              >
                <span
                  className="codicon codicon-python"
                  style={{ color: "var(--cyan)" }}
                ></span>

                {children}
              </Chip>
            );
          }
          if (isTargetFunction) {
            return (
              <Chip
                onClick={(e) => e.stopPropagation()}
                style={{ background: "var(--code-block-bg" }}
              >
                <span className="codicon codicon-symbol-method"></span>
                {children}
              </Chip>
            );
          }
          return (
            <code className={className} {...props}>
              {children}
            </code>
          );
        },
      }),
      [],
    );

    return (
      <div className={styles.markdown}>
        <ReactMarkdown
          remarkPlugins={[
            remarkGfm,
            // () => {
            // 	return (tree: any) => {
            // 		visit(tree, "code", (node: any) => {
            // 			if (!node.lang) {
            // 				node.lang = "text"
            // 			} else if (node.lang.includes(".")) {
            // 				node.lang = node.lang.split(".").slice(-1)[0]
            // 			}
            // 		})
            // 	}
            // },
          ]}
          components={components}
        >
          {markdown || ""}
        </ReactMarkdown>
      </div>
    );
  },
);

export default MarkdownBlock;
