"use client";

import { useRef } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import remarkBreaks from "remark-breaks";
import { cn } from "@/lib/utils";

// Flip the Nth GFM task-list checkbox in the raw markdown source.
function toggleTask(src: string, index: number): string {
  let i = -1;
  return src.replace(/^(\s*[-*+]\s+)\[( |x|X)\]/gm, (match, prefix, mark) => {
    i += 1;
    if (i === index) return `${prefix}[${mark === " " ? "x" : " "}]`;
    return match;
  });
}

/**
 * Renders note/comment/issue content as GitHub-flavored markdown (bullets,
 * task-list checkboxes, etc.). When `onChange` is provided, checkboxes are
 * interactive and toggling one returns the updated markdown source.
 */
export function Markdown({
  content,
  onChange,
  className,
}: {
  content: string;
  onChange?: (next: string) => void;
  className?: string;
}) {
  // Assigns a stable index to each checkbox in document order per render.
  const counter = useRef(0);
  counter.current = 0;

  return (
    <div className={cn("space-y-1 text-sm text-foreground/90", className)}>
      <ReactMarkdown
        remarkPlugins={[remarkGfm, remarkBreaks]}
        components={{
          p: (props) => <p {...props} />,
          h1: (props) => (
            <h1 className="mt-1.5 mb-0.5 text-base font-bold" {...props} />
          ),
          h2: (props) => (
            <h2 className="mt-1.5 mb-0.5 text-sm font-bold" {...props} />
          ),
          h3: (props) => (
            <h3 className="mt-1.5 mb-0.5 text-sm font-semibold" {...props} />
          ),
          h4: (props) => (
            <h4 className="mt-1 text-sm font-semibold" {...props} />
          ),
          h5: (props) => (
            <h5
              className="mt-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground"
              {...props}
            />
          ),
          h6: (props) => (
            <h6
              className="mt-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground"
              {...props}
            />
          ),
          a: (props) => (
            <a
              className="underline underline-offset-2"
              target="_blank"
              rel="noreferrer"
              // Don't let a link click bubble to a clickable row/cell.
              onClick={(e) => e.stopPropagation()}
              {...props}
            />
          ),
          ul: (props) => (
            <ul className="list-disc space-y-0.5 pl-5" {...props} />
          ),
          ol: (props) => (
            <ol className="list-decimal space-y-0.5 pl-5" {...props} />
          ),
          li: ({ className: c, ...props }) => (
            <li
              className={cn(
                "marker:text-muted-foreground",
                // Task-list items drop the bullet and lay out with the checkbox;
                // plain bullets in the same list keep their marker.
                (c || "").includes("task-list-item") &&
                  "flex list-none items-start gap-1.5",
              )}
              {...props}
            />
          ),
          code: (props) => (
            <code className="rounded bg-muted px-1 py-0.5 text-xs" {...props} />
          ),
          input: ({ type, checked }) => {
            if (type !== "checkbox") return null;
            const index = counter.current;
            counter.current += 1;
            return (
              <input
                type="checkbox"
                checked={Boolean(checked)}
                disabled={!onChange}
                onChange={() => onChange?.(toggleTask(content, index))}
                className="mt-1 size-3.5 shrink-0 accent-foreground"
              />
            );
          },
        }}
      >
        {content}
      </ReactMarkdown>
    </div>
  );
}
