import { InfoCardProps } from '@junwon/centum/types'
import { useRouter } from 'solito/router'
import { Paragraph, YStack, XStack, isWeb, Anchor } from 'tamagui'

function CardTitle({ title }: { title: string }) {
  const cardTitleStyle = isWeb
    ? {
        fontFamily: 'Spline+Sans',
        fontWeight: 500,
      }
    : { fontFamily: 'SplineSansMedium' }

  return (
    <Paragraph
      style={cardTitleStyle}
      transform={[{ scaleX: 1.03 }, { scaleY: 0.97 }]}
      size="$8"
      letterSpacing={0.3}
      lineHeight={isWeb ? '$8' : '$9'}
      flex={1}
    >
      {title}
    </Paragraph>
  )
}

function CardBody({
  body,
  onLinkPress,
}: {
  body: string[]
  onLinkPress?: (topic: string) => void
}) {
  const router = useRouter()
  const cardContentStyle = isWeb
    ? {
        fontFamily: 'Spline+Sans',
        fontWeight: 300,
      }
    : { fontFamily: 'SplineSansLight' }

  const renderLinks = (content_parts: (string | JSX.Element)[]): (string | JSX.Element)[] => {
    return content_parts
      .map((content) => {
        if (typeof content !== 'string') return content

        const linkColor = '#06CAEB'
        const internalLinkRegex = /(\{(.*?)\}\[(.*?)\])/g
        const externalLinkRegex = /(\{(.*?)\}\((.*?)\))/g
        const parts: (string | JSX.Element)[] = []
        let lastIndex = 0

        // Process external links
        content.replace(externalLinkRegex, (match, _, display_text, external_link, index) => {
          if (index > lastIndex) {
            parts.push(content.slice(lastIndex, index))
          }
          lastIndex = index + match.length

          parts.push(
            <Anchor
              key={`link-ext-${index}`}
              href={external_link}
              style={{ color: linkColor, ...cardContentStyle }}
              transform={[{ scaleX: 1.03 }, { scaleY: 0.95 }]}
              fontSize="$5"
              letterSpacing={0.3}
              lineHeight={isWeb ? '$6' : '$8'}
              textDecorationLine="none"
            >
              {display_text}
            </Anchor>
          )
          return match
        })

        // Process internal links
        content.replace(
          internalLinkRegex,
          (match, fullMatch, display_text, internal_link, index) => {
            if (index > lastIndex) {
              parts.push(content.slice(lastIndex, index))
            }
            lastIndex = index + match.length

            parts.push(
              <Paragraph
                key={`link-int-${index}`}
                style={{ color: linkColor, ...cardContentStyle }}
                transform={[{ scaleX: 1.03 }, { scaleY: 0.95 }]}
                size="$5"
                letterSpacing={0.3}
                lineHeight={isWeb ? '$6' : '$8'}
                userSelect="none"
                onPress={() => router.push(`/${internal_link}`)}
              >
                {display_text}
              </Paragraph>
            )
            return match
          }
        )

        parts.push(content.slice(lastIndex))
        return parts
      })
      .flat()
  }

  const renderOldLinks = (content: string): (string | JSX.Element)[] => {
    const linkColor = '#06CAEB'
    const regex = /(\{\{(.*?)\|(.*?)\}\}|\[\[(.*?)\|(.*?)\]\])/g
    const parts: (string | JSX.Element)[] = []
    let lastIndex = 0

    content.replace(
      regex,
      (
        match,
        _,
        display_text_ext,
        destination_link,
        display_text_int,
        destination_topic,
        index
      ) => {
        parts.push(content.slice(lastIndex, index))
        lastIndex = index + match.length
        if (match.startsWith('{{')) {
          parts.push(
            <Anchor
              href={destination_link}
              style={{ color: linkColor, ...cardContentStyle }}
              transform={[{ scaleX: 1.03 }, { scaleY: 0.95 }]}
              fontSize="$5"
              letterSpacing={0.3}
              lineHeight={isWeb ? '$6' : '$8'}
              textDecorationLine="none"
            >
              {display_text_ext}
            </Anchor>
          )
        } else if (match.startsWith('[[')) {
          parts.push(
            <Paragraph
              style={{ color: linkColor, ...cardContentStyle }}
              transform={[{ scaleX: 1.03 }, { scaleY: 0.95 }]}
              size="$5"
              letterSpacing={0.3}
              lineHeight={isWeb ? '$6' : '$8'}
              userSelect="none"
              onPress={() => onLinkPress && onLinkPress(destination_topic)}
            >
              {display_text_int}
            </Paragraph>
          )
        }
        return match
      }
    )

    parts.push(content.slice(lastIndex))
    return parts
  }

  return (
    <YStack
      gap="$2"
      maxWidth="100%"
    >
      {body.map((content, index) => (
        <Paragraph
          key={index}
          style={cardContentStyle}
          transform={[{ scaleX: 1.03 }, { scaleY: 0.95 }]}
          size="$5"
          letterSpacing={0.3}
          lineHeight={isWeb ? '$6' : '$8'}
        >
          {renderLinks(renderOldLinks(content))}
        </Paragraph>
      ))}
    </YStack>
  )
}

export const InfoCard = (props: InfoCardProps) => {
  return (
    <YStack
      width="100%"
      gap="$3"
    >
      <XStack
        jc="space-between"
        ai="flex-start"
        gap="$3"
      >
        <CardTitle title={props.title} />
      </XStack>
      <CardBody
        body={props.contents}
        onLinkPress={props.onLinkPress}
      />
    </YStack>
  )
}
