import React, { useMemo } from 'react'

import { format } from '@baurine/sql-formatter-plus'
import { Prism } from '@tidbcloud/uikit'

export function formatSql(sql?: string): string {
  let formatedSQL = sql || ''
  try {
    formatedSQL = format(sql || '', { uppercase: true, language: 'tidb' })
  } catch (_e) {
    console.log(sql)
  }
  return formatedSQL
}

export 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, '*/')
}

export function compactSql(sql?: string): string {
  return simpleSqlMinify(formatSql(sql))
}

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

function HighlightSQL({ sql, compact, format = true }: Props) {
  const formattedSql = useMemo(() => {
    if (!format) {
      return compact ? simpleSqlMinify(sql) : sql
    }

    return compact ? compactSql(sql) : formatSql(sql)
  }, [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 default React.memo(HighlightSQL)
