import { Highlight, Language, PrismTheme, themes } from "prism-react-renderer";
import React from "react";

import "./styles/style.scss";

interface CodeProps {
  /** Code to highlight. */
  children?: string;
  /** Supported languages. */
  language?: Language;
  /** Inline code preview with text. */
  inline?: boolean;
  /** Theme VSCode theme style object defined in https://github.com/FormidableLabs/prism-react-renderer#theming */
  theme?: PrismTheme;
  [key: string]: any;
}

interface RenderProps {
  tokens: any[][];
  style: React.CSSProperties;
  getLineProps: (props: { line: any[]; key: number }) => any;
  getTokenProps: (props: { token: any; key: number }) => any;
}

const PreviewCode: React.FC<CodeProps> = ({
  children,
  language = "markup",
  inline = false, // Changed default to false - let MDX components decide
  theme = themes.oneLight,
  ...other
}) => {
  if (!children) {
    return null;
  }

  // Trim trailing whitespace/newlines to prevent empty lines
  const trimmedCode = children.trim();

  const CodeTag = inline ? "span" : "div";

  return (
    <Highlight code={trimmedCode} language={language} theme={theme}>
      {({ tokens, style, getLineProps, getTokenProps }: RenderProps) => {
        const highlight = tokens.map((line, i) => (
          <CodeTag {...getLineProps({ line, key: i })} key={i}>
            {line.map((token, key) => {
              const tokenProps = getTokenProps({ token, key });
              // Nahradiť "tag" s "code-tag" v className
              if (
                tokenProps.className &&
                tokenProps.className.includes("tag")
              ) {
                tokenProps.className = tokenProps.className.replace(
                  /\btag\b/g,
                  "code-tag",
                );
              }
              return <span {...tokenProps} key={key} />;
            })}
          </CodeTag>
        ));

        const WrapperTag = inline ? "span" : "div";

        return (
          <WrapperTag
            className={`code-wrapper code-container ${inline ? "inline" : "block"}`}
            style={style}
            {...other}
          >
            {inline ? (
              <code
                className={`code code--inline prism-code language-${language} code-inline`}
              >
                {highlight}
              </code>
            ) : (
              <pre className={`language-${language} pre-block`}>
                <code
                  className={`code prism-code language-${language} code-block`}
                >
                  {highlight}
                </code>
              </pre>
            )}
          </WrapperTag>
        );
      }}
    </Highlight>
  );
};

PreviewCode.displayName = "Code";

export { PreviewCode };
