import type { Components } from 'react-markdown'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { Link } from 'react-router-dom'

const markdownComponents: Components = {
  a: ({ href, children }) => {
    if (href?.startsWith('/')) {
      return (
        <Link to={href} className="ac-link font-semibold">
          {children}
        </Link>
      )
    }
    return (
      <a href={href} target="_blank" rel="noopener noreferrer" className="ac-link">
        {children}
      </a>
    )
  },
  p: ({ children }) => <p className="ac-islander-markdown__p">{children}</p>,
  ul: ({ children }) => <ul className="ac-islander-markdown__ul">{children}</ul>,
  ol: ({ children }) => <ol className="ac-islander-markdown__ol">{children}</ol>,
  li: ({ children }) => <li className="ac-islander-markdown__li">{children}</li>,
  h1: ({ children }) => <h3 className="ac-islander-markdown__h">{children}</h3>,
  h2: ({ children }) => <h3 className="ac-islander-markdown__h">{children}</h3>,
  h3: ({ children }) => <h4 className="ac-islander-markdown__h4">{children}</h4>,
  code: ({ className, children }) => {
    const isBlock = className?.includes('language-')
    if (isBlock) {
      return <code className={`ac-islander-markdown__code-block ${className ?? ''}`}>{children}</code>
    }
    return <code className="ac-islander-markdown__code">{children}</code>
  },
  pre: ({ children }) => <pre className="ac-islander-markdown__pre">{children}</pre>,
  blockquote: ({ children }) => (
    <blockquote className="ac-islander-markdown__quote">{children}</blockquote>
  ),
  hr: () => <hr className="ac-islander-markdown__hr" />,
  table: ({ children }) => (
    <div className="ac-islander-markdown__table-wrap">
      <table className="ac-islander-markdown__table">{children}</table>
    </div>
  ),
  th: ({ children }) => <th className="ac-islander-markdown__th">{children}</th>,
  td: ({ children }) => <td className="ac-islander-markdown__td">{children}</td>,
}

type IslanderMarkdownProps = {
  content: string
}

export function IslanderMarkdown({ content }: IslanderMarkdownProps) {
  if (!content.trim()) return null

  return (
    <div className="ac-islander-markdown text-sm leading-relaxed text-ink">
      <ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
        {content}
      </ReactMarkdown>
    </div>
  )
}