import React from 'react'
import Link from 'next/link'

interface RenderState {
  currentList: string[]
  inCodeBlock: boolean
  codeBlockContent: string[]
}

export function renderMarkdown(markdown: string): JSX.Element[] {
  const lines = markdown.split('\n')
  const elements: JSX.Element[] = []
  const state: RenderState = {
    currentList: [],
    inCodeBlock: false,
    codeBlockContent: [],
  }

  lines.forEach((line, index) => {
    if (line.startsWith('```')) {
      handleCodeBlock(line, index, state, elements)
      return
    }

    if (state.inCodeBlock) {
      state.codeBlockContent.push(line)
      return
    }

    closeListIfNeeded(line, index, state, elements)

    if (line.startsWith('# ')) {
      elements.push(<h1 key={index} className="text-3xl font-bold mt-8 mb-4">{line.substring(2)}</h1>)
    } else if (line.startsWith('## ')) {
      elements.push(<h2 key={index} className="text-2xl font-bold mt-6 mb-3">{line.substring(3)}</h2>)
    } else if (line.startsWith('### ')) {
      elements.push(<h3 key={index} className="text-xl font-semibold mt-4 mb-2">{line.substring(4)}</h3>)
    } else if (line.startsWith('#### ')) {
      elements.push(<h4 key={index} className="text-lg font-semibold mt-3 mb-2">{line.substring(5)}</h4>)
    } else if (line.startsWith('- ') || line.startsWith('* ')) {
      state.currentList.push(line)
    } else if (line.includes('[') && line.includes('](')) {
      renderLink(line, index, elements)
    } else if (line.includes('**') || line.includes('`')) {
      renderBoldAndCode(line, index, elements)
    } else if (line.trim() !== '') {
      elements.push(<p key={index} className="mb-4 text-gray-700">{line}</p>)
    } else if (elements.length > 0 && elements[elements.length - 1].type !== 'br') {
      elements.push(<br key={`br-${index}`} />)
    }
  })

  closeListIfNeeded('', lines.length, state, elements)

  return elements
}

function handleCodeBlock(
  line: string,
  index: number,
  state: RenderState,
  elements: JSX.Element[]
): void {
  if (state.inCodeBlock) {
    elements.push(
      <pre key={`code-${index}`} className="bg-gray-100 p-4 rounded-lg overflow-x-auto my-4">
        <code>{state.codeBlockContent.join('\n')}</code>
      </pre>
    )
    state.codeBlockContent = []
    state.inCodeBlock = false
  } else {
    state.inCodeBlock = true
  }
}

function closeListIfNeeded(
  line: string,
  index: number,
  state: RenderState,
  elements: JSX.Element[]
): void {
  if (state.currentList.length > 0 && !line.startsWith('- ') && !line.startsWith('* ') && line.trim() !== '') {
    elements.push(
      <ul key={`list-${index}`} className="list-disc list-inside mb-4 space-y-1">
        {state.currentList.map((item, i) => (
          <li key={i} className="ml-4">{item.substring(2).trim()}</li>
        ))}
      </ul>
    )
    state.currentList = []
  }
}

function createLinkElement(
  text: string,
  href: string,
  key: string,
  isExternal: boolean
): JSX.Element {
  const className = 'text-blue-600 hover:text-blue-800 underline'
  if (isExternal) {
    return (
      <a key={key} href={href} target="_blank" rel="noopener noreferrer" className={className}>
        {text}
      </a>
    )
  }
  return (
    <Link key={key} href={href} className={className}>
      {text}
    </Link>
  )
}

function renderLink(line: string, index: number, elements: JSX.Element[]): void {
  const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g
  let lastIndex = 0
  const parts: (string | JSX.Element)[] = []
  let match

  while ((match = linkRegex.exec(line)) !== null) {
    if (match.index > lastIndex) {
      parts.push(line.substring(lastIndex, match.index))
    }
    const href = match[2]
    const isExternal = href.startsWith('http')
    parts.push(createLinkElement(match[1], href, `link-${index}-${match.index}`, isExternal))
    lastIndex = match.index + match[0].length
  }

  if (lastIndex < line.length) {
    parts.push(line.substring(lastIndex))
  }

  elements.push(<p key={index} className="mb-4">{parts}</p>)
}

function renderBoldAndCode(line: string, index: number, elements: JSX.Element[]): void {
  const parts: (string | JSX.Element)[] = []
  const codeRegex = /`([^`]+)`/g
  let codeMatch
  let lastIndex = 0

  while ((codeMatch = codeRegex.exec(line)) !== null) {
    if (codeMatch.index > lastIndex) {
      const beforeCode = line.substring(lastIndex, codeMatch.index)
      processBold(beforeCode, parts)
    }
    parts.push(
      <code key={`code-${codeMatch.index}`} className="bg-gray-100 px-1 py-0.5 rounded text-sm font-mono">
        {codeMatch[1]}
      </code>
    )
    lastIndex = codeMatch.index + codeMatch[0].length
  }

  if (lastIndex < line.length) {
    const remaining = line.substring(lastIndex)
    processBold(remaining, parts)
  }

  elements.push(<p key={index} className="mb-4">{parts.length > 0 ? parts : line}</p>)
}

function processBold(text: string, parts: (string | JSX.Element)[]): void {
  const boldParts = text.split(/(\*\*[^*]+\*\*)/g)
  boldParts.forEach((part, i) => {
    if (part.startsWith('**') && part.endsWith('**')) {
      parts.push(<strong key={`bold-${i}`}>{part.slice(2, -2)}</strong>)
    } else if (part) {
      parts.push(part)
    }
  })
}
