import React from 'react'
import { twMerge } from 'tailwind-merge'
import withDefaults from '../utils/with-defaults'

interface Props {
  block?: boolean
  width?: string
  className?: string
}

const defaultProps = {
  block: false,
  className: ''
}

type NativeAttrs = Omit<React.HTMLAttributes<any>, keyof Props>
export type CodeProps = Props & typeof defaultProps & NativeAttrs

const Code: React.FC<React.PropsWithChildren<CodeProps>> = ({
  children,
  block,
  className,
  width,
  ...props
}) => {
  const themeClassNames =
    'bg-grayscale-2 text-grayscale-10 dark:bg-overlay-white-5 dark:text-overlay-white-11'

  if (!block)
    return (
      <code className={twMerge('p1 rounded-sm', themeClassNames, className)} {...props}>
        {children}
      </code>
    )

  return (
    <>
      <pre className={twMerge('rounded p-2', themeClassNames, className)} {...props}>
        <code>{children}</code>
      </pre>
      <style jsx>{`
        pre {
          width: ${width ? width : 'initial'};
          max-width: 100%;
        }
      `}</style>
    </>
  )
}

const MemoCode = React.memo(Code)

export default withDefaults(MemoCode, defaultProps)
