import { t } from '@lingui/core/macro';
import {
  ActionIcon,
  type ActionIconVariant,
  Button,
  type DefaultMantineColor,
  type FloatingPosition,
  CopyButton as MantineCopyButton,
  type MantineSize,
  Text,
  Tooltip
} from '@mantine/core';
import { IconCheck, IconCopy } from '@tabler/icons-react';

import type { JSX } from 'react';

export function CopyButton({
  value,
  label,
  tooltip,
  disabled,
  tooltipPosition,
  content,
  size,
  color = 'gray',
  variant = 'transparent'
}: Readonly<{
  value: any;
  label?: string;
  tooltip?: string;
  disabled?: boolean;
  tooltipPosition?: FloatingPosition;
  content?: JSX.Element;
  size?: MantineSize;
  color?: DefaultMantineColor;
  variant?: ActionIconVariant;
}>) {
  const ButtonComponent = label ? Button : ActionIcon;

  // Disable the copy button if we are not in a secure context, as the Clipboard API is not available
  if (!window.isSecureContext) {
    return null;
  }

  return (
    <MantineCopyButton value={value}>
      {({ copied, copy }) => (
        <Tooltip
          label={copied ? t`Copied` : (tooltip ?? t`Copy`)}
          withArrow
          position={tooltipPosition}
        >
          <ButtonComponent
            disabled={disabled}
            color={copied ? 'teal' : color}
            onClick={(e: any) => {
              e.stopPropagation();
              e.preventDefault();
              copy();
            }}
            variant={copied ? 'transparent' : (variant ?? 'transparent')}
            size={size ?? 'sm'}
          >
            {copied ? <IconCheck /> : <IconCopy />}
            {content}
            {label && (
              <Text p={size ?? 'sm'} size={size ?? 'sm'}>
                {label}
              </Text>
            )}
          </ButtonComponent>
        </Tooltip>
      )}
    </MantineCopyButton>
  );
}
