import { MDXRemote } from "remote-mdx/rsc";
import { CodeHighlighter } from "@/app/components/code-highlighter";
import { Separator } from "@/app/components/ui/separator";
import { cn } from "@/common/utils";
import Link from "next/link";

/**
 * Create a heading component.
 *
 * @param level the level of the heading.
 */
function createHeading(level: number) {
  // eslint-disable-next-line react/display-name
  return (props: any) => {
    const Tag = `h${level}`;
    return (
      <div className={cn("pb-4", level > 1 ? "pt-6" : null)}>
        <Tag className={`text-${4 - level}xl font-semibold pb-2`} {...props} />
        <Separator />
      </div>
    );
  };
}

/**
 * The components to use in the MDX renderer.
 */
const components = {
  h1: (props: any) => createHeading(1)(props),
  h2: (props: any) => createHeading(2)(props),
  code: (props: any) => {
    if (!props.className) {
      return <code className="text-xs bg-secondary p-1 rounded-md leading-none" {...props} />;
    }

    return (
      <div className="pt-4">
        <CodeHighlighter
          language={props.className ? props.className.replace("language-") : undefined}
          code={props.children}
        />
      </div>
    );
  },
  ul: (props: any) => <ul className="list-disc pl-4 py-2">{props.children}</ul>,
  a: (props: any) => (
    <Link href={props.href} className="text-primary hover:opacity-85 transition-all transform-gpu">
      {props.children}
    </Link>
  ),
};

export function CustomMDX(props: any) {
  return <MDXRemote {...props} components={{ ...components, ...(props.components || {}) }} />;
}
