import React, { useMemo } from 'react'

import {
  Box,
  HoverCard,
  HoverCardProps,
  Prism,
  Typography
} from '@tidbcloud/uikit'

import formatSql from '~/utils/sql-formatter'

function simpleSqlMinify(str: string) {
  return str
    .replace(/\s{1,}/g, ' ')
    .replace(/\{\s{1,}/g, '{')
    .replace(/\}\s{1,}/g, '}')
    .replace(/;\s{1,}/g, ';')
    .replace(/\/\*\s{1,}/g, '/*')
    .replace(/\*\/\s{1,}/g, '*/')
}

interface HighlightSQLProps {
  sql: string
  compact?: boolean
  format?: boolean
}

function HighlightSQL({ sql, compact, format = true }: HighlightSQLProps) {
  const formattedSql = useMemo(() => {
    let f = format ? formatSql(sql) : sql
    if (compact) {
      f = simpleSqlMinify(f)
    }
    return f
  }, [sql, compact, format])

  return (
    <Prism
      noCopy
      language='sql'
      styles={{
        code: {
          backgroundColor: 'transparent !important',
          padding: 0,
          fontSize: compact ? 13 : 12
        },
        scrollArea: {
          '& > div > div': {
            display: compact ? 'block !important' : undefined
          }
        },
        line: {
          padding: 0
        },
        lineContent: compact
          ? {
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis'
            }
          : {}
      }}
    >
      {formattedSql}
    </Prism>
  )
}

export function SQLWithPopover({
  sql,
  position
}: {
  sql: string
  position?: HoverCardProps['position']
}) {
  const truncSQLShort = useMemo(() => {
    return sql.length <= 200 ? sql : sql.slice(0, 200) + '...'
  }, [sql])
  const truncSQLLong = useMemo(() => {
    return sql.length <= 1000 ? sql : sql.slice(0, 1000) + '...'
  }, [sql])

  return (
    <Box w='100%'>
      <HoverCard
        withinPortal
        withArrow
        position={position || 'right'}
        shadow='md'
      >
        <HoverCard.Target>
          <Box>
            <HighlightSQL sql={truncSQLShort} compact />
          </Box>
        </HoverCard.Target>
        <HoverCard.Dropdown
          onClick={(e) => e.stopPropagation()}
          maw={700}
          mah='90vh'
          sx={{ overflow: 'auto' }}
        >
          <HighlightSQL sql={truncSQLLong} />
        </HoverCard.Dropdown>
      </HoverCard>
    </Box>
  )
}

// the evicted record's digest is empty string
export function EvictedSQL() {
  return (
    <HoverCard withinPortal withArrow position='right' shadow='md'>
      <HoverCard.Target>
        <Typography c='dimmed' fs='italic'>
          Others
        </Typography>
      </HoverCard.Target>
      <HoverCard.Dropdown onClick={(e) => e.stopPropagation()}>
        <Typography>All of other dropped SQL statements</Typography>
      </HoverCard.Dropdown>
    </HoverCard>
  )
}
