import type { JSX } from 'react';
import { Tooltip } from '@mui/material';
import { green } from '@mui/material/colors';
import { ContentCopy as CopyIcon, Check as CheckIcon } from '@mui/icons-material';
import useCopy from './hook';
import type { Locale } from '../type';

export interface CopyButtonProps extends React.HTMLAttributes<HTMLSpanElement> {
  content?: string;
  locale?: Locale;
  render?: (props: { copyButton: React.ReactNode; containerRef: React.Ref<unknown> }) => JSX.Element | null;
  showTooltip?: true | false;
}

export default function CopyButton({
  content = '',
  locale = 'en',
  render = undefined,
  showTooltip = true,
  ...rest
}: CopyButtonProps) {
  const { containerRef, copied, copy, texts } = useCopy({ content, locale });
  const iconStyle = {
    fontSize: '1em',
  };

  const copyButton = (
    <span title={copied ? '' : texts.copy} {...rest} style={{ height: '1em', ...rest.style }}>
      {copied ? (
        <Tooltip title={texts.copied} placement="bottom" arrow open={copied && showTooltip}>
          <CheckIcon sx={{ ...iconStyle, color: green[500] }} />
        </Tooltip>
      ) : (
        <CopyIcon onClick={copy} sx={{ ...iconStyle, cursor: 'pointer' }} />
      )}
    </span>
  );

  if (render) {
    return render({ copyButton, containerRef });
  }
  return copyButton;
}
