"use client";
import React, { useEffect, useRef, 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 rehypeRaw from "rehype-raw";

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

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

  // Fetch content
  useEffect(() => {
    hasExtractedHeadings.current = false;
    (async () => {
      const res = await fetch(`/api/content?path=${encodeURIComponent(contentPath)}`);
      const text = await res.text();
      // Just get the content without frontmatter
      const frontmatterMatch = text.match(/^---\n[\s\S]*?\n---\n/);
      const content = frontmatterMatch ? text.slice(frontmatterMatch[0].length) : text;
      setSource(content);
    })();
  }, [contentPath]);

  // Extract headings from rendered DOM after content is rendered
  useEffect(() => {
    if (!source || !articleRef.current || !onHeadings || hasExtractedHeadings.current) return;

    // Use a small delay to ensure rehype-slug has processed the headings
    const timeoutId = setTimeout(() => {
      if (!articleRef.current) return;
      
      const headingElements = articleRef.current.querySelectorAll("h1, h2, h3, h4, h5, h6");
      const headings: { id: string; text: string; level: number }[] = [];
      
      headingElements.forEach((el) => {
        const id = el.getAttribute("id");
        const text = el.textContent?.trim() || "";
        const level = parseInt(el.tagName[1], 10);
        
        if (id && text) {
          headings.push({ id, text, level });
        }
      });
      
      hasExtractedHeadings.current = true;
      onHeadings(headings);
    }, 50);

    return () => clearTimeout(timeoutId);
  }, [source, 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} />
    ),
    iframe: ({ src, ...props }: any) => (
      <iframe src={src} className="markdown-iframe" {...props} />
    ),
  };

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