import { type RichTextItemResponse } from '@notionhq/client/build/src/api-endpoints'
import clsx from 'clsx'
import dynamic from 'next/dynamic'
import { type FC, Suspense } from 'react'

import HybridLink from './HybridLink'

const TeX = dynamic(() => import('@matejmazur/react-katex'))

const RichText: FC<{ richText: RichTextItemResponse[] }> = ({ richText }) => {
  return (
    <>
      {richText.map((text, index) => {
        if (text.type === 'mention') return null // TODO
        else if (text.type === 'text') {
          const className = clsx({
            italic: text.annotations.italic,
            'font-bold': text.annotations.bold,
            underline: text.annotations.underline,
            'dark:bg-neutral-800 border-1 dark:border-neutral-500 font-mono dark:text-red-400 p-1 rounded':
              text.annotations.code,
          })

          if (text.href) {
            return (
              <HybridLink
                key={index}
                href={text.href}
                className={clsx(
                  'underline transition-colors dark:hover:text-teal-500',
                  className,
                )}
              >
                {text.plain_text}
              </HybridLink>
            )
          }

          const Tag = text.annotations.strikethrough ? 's' : 'span'
          return (
            <Tag key={index} className={className}>
              {text.plain_text}
            </Tag>
          )
        } else if (text.type === 'equation')
          return (
            <Suspense key={index} fallback="Loading...">
              <TeX block={false}>{text.equation.expression}</TeX>
            </Suspense>
          )
      })}
    </>
  )
}

export default RichText
