import React from 'react'

import {
  ActionIcon,
  Anchor,
  Box,
  Card,
  CardProps,
  Code,
  CopyButton,
  Text,
  Tooltip
} from '@mantine/core'
// import { CodeBlock } from '@mantine/core/biz'
import { IconCheck, IconCopy } from '@tabler/icons-react'
import ReactMarkdown from 'react-markdown'
import { Prism } from 'react-syntax-highlighter'
import remarkGfm from 'remark-gfm'

import Feedback from '../Feedback'
import LinguflowFeedback from '../LinguflowFeedback'
import { Message, useChatStream } from './useMessages'

export const AssistantMessage: React.FC<{
  msg: Message
  generating: boolean
  error: any
  alwaysShowFeedback?: boolean
  onStreamFinished: (m: string) => void
  onStreamChange: () => void
  onStreamError: (e: any) => void
  onRegenerate: () => void
  onLike: () => void
  onDislike: () => void
  onOpenFeedback: () => void
  isLinguflowApp?: boolean
}> = ({
  msg: message,
  generating,
  error,
  alwaysShowFeedback,
  onStreamFinished,
  onStreamChange,
  onStreamError,
  onRegenerate,
  onLike,
  onDislike,
  onOpenFeedback,
  isLinguflowApp
}) => {
  const { messageValue } = useChatStream({
    msg: message,
    onChange: onStreamChange,
    onFinished: onStreamFinished,
    onError: onStreamError
  })

  return (
    <Card
      maw='95%'
      px='md'
      py='xs'
      fz='sm'
      bg='gray.1'
      c='gray.8'
      shadow='none'
      sx={{
        position: 'relative',
        flexShrink: 0,
        alignSelf: 'start',
        overflow: 'visible',
        wordBreak: 'break-word'
      }}
      withBorder={false}
    >
      {!error ? (
        <>
          {isLinguflowApp ? (
            <LinguflowFeedback message={message} />
          ) : (
            <Feedback message={message} />
          )}

          <CustomMarkdown content={messageValue} />
          {generating && <Text c='gray.5'>AI Generating...</Text>}
        </>
      ) : (
        <Text>
          Sorry, the OpenAI server has reached the rate limit for now. Please
          try again later by clicking on "
          <Anchor onClick={onRegenerate}>Regenerate</Anchor>".
        </Text>
      )}
    </Card>
  )
}

export const UserMessage: React.FC<{ msg: Message }> = ({ msg }) => {
  return (
    <Card
      maw='95%'
      px='md'
      py='xs'
      fz='sm'
      bg='blue.0'
      c='gray.8'
      shadow='none'
      sx={{
        flexShrink: 0,
        alignSelf: 'end',
        whiteSpace: 'pre-wrap',
        wordBreak: 'break-word'
      }}
      withBorder={false}
    >
      {msg.displayed.content}
    </Card>
  )
}

const CustomMarkdown: React.FC<{
  content: string
}> = ({ content }) => {
  return (
    <ReactMarkdown
      children={content}
      remarkPlugins={[remarkGfm]}
      components={{
        a({ children, ...props }) {
          return (
            <Anchor {...props} target='_blank' sx={{ wordBreak: 'break-all' }}>
              {children}
            </Anchor>
          )
        },
        pre({ children }) {
          return <>{children}</>
        },
        code({ node, inline, children, lang, ...props }) {
          return inline ? (
            <Code
              {...props}
              sx={(theme) => ({
                backgroundColor:
                  theme.colorScheme === 'dark' ? theme.black : theme.white
              })}
            >
              {children}
            </Code>
          ) : (
            <Box pos='relative'>
              <CopyButton
                value={children.map((c) => c as string).join('\n')}
                timeout={2000}
              >
                {({ copied, copy }) => (
                  <Tooltip
                    label={copied ? 'Copied' : 'Copy'}
                    withArrow
                    position='right'
                  >
                    <ActionIcon
                      pos='absolute'
                      style={{ top: '10px', right: '10px' }}
                      color={copied ? 'teal' : 'gray'}
                      variant='light'
                      onClick={copy}
                    >
                      {copied ? (
                        <IconCheck style={{ width: '70%', height: '70%' }} />
                      ) : (
                        <IconCopy style={{ width: '70%', height: '70%' }} />
                      )}
                    </ActionIcon>
                  </Tooltip>
                )}
              </CopyButton>
              <Prism language={lang as any}>
                {children.map((c) => c as string).join('\n')}
              </Prism>
            </Box>
          )
        }
      }}
    />
  )
}

export const TipsMessage: React.FC<React.PropsWithChildren<CardProps>> = ({
  children,
  ...props
}) => {
  return (
    <Card
      maw='95%'
      px='md'
      py='xs'
      fz='sm'
      bg='gray.1'
      c='gray.8'
      shadow='none'
      sx={{ flexShrink: 0, alignSelf: 'start' }}
      withBorder={false}
      {...props}
    >
      {children}
    </Card>
  )
}

export const ActionMessage: React.FC<
  React.PropsWithChildren<{ onClick?: () => void }>
> = ({ children, onClick }) => {
  return (
    <Card
      maw='95%'
      px='xs'
      py={2}
      fz={12}
      c='blue.3'
      shadow='none'
      sx={(theme) => ({
        flexShrink: 0,
        alignSelf: 'end',
        cursor: 'pointer',
        border: `1px solid ${theme.colors.blue[3]}`,
        ':hover': {
          color: theme.colors.blue[6],
          borderColor: theme.colors.blue[6]
        }
      })}
      onClick={onClick}
    >
      {children}
    </Card>
  )
}
