import {
  ActionIcon,
  ActionIconProps,
  Code,
  CodeProps,
  CopyButton,
  Group,
  Tooltip,
  ElementProps
} from '@tidbcloud/uikit'
import { IconCheck, IconCopy01 } from '@tidbcloud/uikit/icons'

/**
 * Custom data attributes
 * https://stackoverflow.com/questions/71663377/which-is-the-best-way-to-define-the-type-of-dynamic-data-attributes-in-a-react-c
 */
interface CodeWithActionProps {
  codeProps?: Omit<CodeProps, 'children'>
  copyIconProps?: Omit<ActionIconProps, 'children'> &
    ElementProps<'button'> & {
      [dataAttr: `data-${string}`]: string
    }
  noCopy?: boolean
  children: string
}

export const CodeWithAction = ({ codeProps = {}, copyIconProps = {}, noCopy, children }: CodeWithActionProps) => {
  return (
    <Group
      gap={0}
      sx={(theme) => {
        const { carbon } = theme.colors

        return {
          color: carbon[8],
          backgroundColor: carbon[1],
          border: `1px solid ${carbon[4]}`,
          borderRadius: 8,
          padding: '2px 2px 2px 8px'
        }
      }}
    >
      <Code fw={600} c="inherit" bg="transparent" {...codeProps}>
        {children}
      </Code>
      {!noCopy && (
        <CopyButton value={children} timeout={2000}>
          {({ copied, copy }) => (
            <Tooltip label={copied ? 'Copied' : 'Copy'} withArrow position="right">
              <ActionIcon
                variant="transparent"
                size="sm"
                c="inherit"
                {...copyIconProps}
                onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
                  copyIconProps?.onClick?.(e)
                  copy()
                }}
              >
                {copied ? <IconCheck size={14} /> : <IconCopy01 size={14} />}
              </ActionIcon>
            </Tooltip>
          )}
        </CopyButton>
      )}
    </Group>
  )
}
