"use client";
import React, { useEffect, useMemo, useState } from "react";
import ReactMarkdown from "react-markdown";
import type { Components } from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeSlug from "rehype-slug";
import rehypeAutolinkHeadings from "rehype-autolink-headings";
import { parseMarkdownWithFrontmatter } from "@/lib/markdown";

type MarkdownRendererProps = {
  contentPath: string;
  onHeadings?: (headings: { id: string; text: string; level: number }[]) => void;
};

export function MarkdownRenderer({ contentPath, onHeadings }: MarkdownRendererProps) {
  const [source, setSource] = useState<string>("");

  useEffect(() => {
    (async () => {
      const res = await fetch(`/api/content?path=${encodeURIComponent(contentPath)}`);
      const text = await res.text();
      const { content, headings } = parseMarkdownWithFrontmatter(text);
      setSource(content);
      onHeadings?.(headings);
    })();
  }, [contentPath, onHeadings]);

  const components: Components = {
    blockquote: ({ children, ...props }) => (
      <blockquote className="markdown-blockquote" {...props}>
        {children}
      </blockquote>
    ),
    code: ({ inline, className, children, ...props }: any) => {
      if (inline) {
        return <code className="markdown-code-inline" {...props}>{children}</code>;
      }
      return (
        <pre className="markdown-pre">
          <code className={className} {...props}>
            {children}
          </code>
        </pre>
      );
    },
    table: ({ children, ...props }) => (
      <div className="markdown-table-wrapper">
        <table className="markdown-table" {...props}>
          {children}
        </table>
      </div>
    ),
    hr: (props) => <hr className="markdown-hr" {...props} />,
    img: ({ src, alt, ...props }) => (
      <img src={src} alt={alt || ""} className="markdown-img" loading="lazy" {...props} />
    ),
  };

  return (
    <article className="markdown-content" aria-label="Conteúdo">
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        rehypePlugins={[rehypeSlug, [rehypeAutolinkHeadings, { behavior: "wrap" }]]}
        components={components}
      >
        {source}
      </ReactMarkdown>
    </article>
  );
}
