import { useSize } from 'ahooks';
import { Tooltip, type TooltipProps } from '@mui/material';
import isUndefined from 'lodash/isUndefined';
import { useSnackbar } from 'notistack';
import useCopy from './hook';
import Toast, { ToastProvider } from '../Toast';
import { mergeProps } from '../Util';
import { styled } from '../Theme';
import type { Locale } from '../type';

export { default as CopyButton } from './copy-button';

const Container = styled('span')`
  display: inline;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-wrap: break-word;
  align-items: center;
  justify-content: start;
  border-radius: 15px;
  padding: 1px 12px;
  background-color: rgba(0, 0, 0, 0.08);
  cursor: pointer;
`;

const UnstyledContainer = styled('span')`
  cursor: pointer;
`;

export interface ClickToCopyProps extends TooltipProps {
  content?: string;
  locale?: Locale;
  tip?: string;
  tipPlacement?: string;
  copiedTip?: string;
  unstyled?: false | true;
}

export default function ClickToCopy(rawProps: ClickToCopyProps) {
  const props = Object.assign({}, rawProps);
  // eslint-disable-next-line react/prop-types
  if (isUndefined(props.content)) {
    props.content = '';
  }
  // eslint-disable-next-line react/prop-types
  if (isUndefined(props.tip)) {
    props.tip = '';
  }
  // eslint-disable-next-line react/prop-types
  if (isUndefined(props.copiedTip)) {
    props.copiedTip = '';
  }
  // eslint-disable-next-line react/prop-types
  if (isUndefined(props.tipPlacement)) {
    props.tipPlacement = 'right';
  }
  // eslint-disable-next-line react/prop-types
  if (isUndefined(props.locale)) {
    props.locale = 'en';
  }
  // eslint-disable-next-line react/prop-types
  if (isUndefined(props.unstyled)) {
    props.unstyled = false;
  }
  const newProps = mergeProps(props, ClickToCopy, ['style']);
  const { children, content, tip, copiedTip, tipPlacement, locale, style, unstyled, ...rest } = newProps;
  const { containerRef, copied, copy, texts } = useCopy({ content, locale });
  const _tip = tip || texts.copy;
  const _copiedTip = copiedTip || texts.copied;
  const snackbarContext = useSnackbar();

  const size = useSize(document.body);
  const width = size?.width || 0;

  const onCopy = (e: React.MouseEvent<HTMLElement>) => {
    copy(e);

    if (width < 600) {
      Toast.success(_copiedTip);
    }
  };

  const ContainerComponent = unstyled ? UnstyledContainer : Container;
  const contentChild = (
    <Tooltip title={copied ? _copiedTip : _tip} {...rest} placement={tipPlacement} disableFocusListener>
      <ContainerComponent ref={containerRef} style={style} onClick={onCopy}>
        {children || content}
      </ContainerComponent>
    </Tooltip>
  );
  if (!snackbarContext) {
    return <ToastProvider>{contentChild}</ToastProvider>;
  }
  // eslint-disable-next-line react/jsx-no-useless-fragment
  return <>{contentChild}</>;
}
