import React, { FC, useState } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import { Flex, FlexProps } from '../Flex';
import { Box } from '../Box';
import { Text } from '../Text';
import { TextEllipsis } from '../TextEllipsis';
import { Link } from '../Link';
import { Icon, IconProps } from '../Icon';
import { SvgCopy, SvgShare } from '../../assets/images/icons';
import { styled } from '../../styles';

export interface Props {
  hash?: string;
  copyLink?: boolean;
  link?: string;
  size?: number;
  flexProps?: FlexProps;
  variant?: 'primary' | 'secondary';
  buttonProps?: { copyId?: string; linkId?: string };
}

export const TransactionHash: FC<Props> = ({
  hash = '',
  copyLink,
  link,
  size,
  flexProps,
  variant = 'primary',
  buttonProps,
}) => {
  const [copied, setCopied] = useState(false);
  const isPrimary = variant === 'primary';

  const handleCopyClick = () => {
    setCopied(true);
    setTimeout(() => {
      setCopied(false);
    }, 2000);
  };

  return (
    <Flex {...flexProps}>
      <Box
        borderRadius="2"
        px="1"
        mr="s"
        {...(isPrimary ? { bg: 'brandLightest' } : {})}
      >
        <Text fontSize="0" color="brandMain">
          {size ? <TextEllipsis size={size}>{hash}</TextEllipsis> : hash}
        </Text>
      </Box>
      <CopyButton text={copyLink && link ? link : hash}>
        <CopyIcon
          {...(buttonProps && buttonProps.copyId
            ? { id: buttonProps.copyId }
            : {})}
          Asset={SvgCopy}
          width={14}
          height={14}
          color="gray.2"
          onClick={handleCopyClick}
          copied={copied}
        />
      </CopyButton>
      {link && (
        <Link
          {...(buttonProps && buttonProps.linkId
            ? { id: buttonProps.linkId }
            : {})}
          href={link}
        >
          <Icon Asset={SvgShare} width={12} height={12} color="gray.2" ml="s" />
        </Link>
      )}
    </Flex>
  );
};

const CopyButton = styled(CopyToClipboard)`
  cursor: pointer;
`;

type CopyIconProps = { copied: boolean } & IconProps;

const CopyIcon = styled(Icon)<CopyIconProps>`
  position: relative;

  &::after {
    content: 'Copied';
    position: absolute;
    top: -25px;
    left: 50%;
    transform: translateX(-50%);
    margin: 0;
    padding: 5px;
    background-color: rgba(0, 0, 0, 0.7);
    color: #ffffff;
    border-radius: 8px;
    font-size: 9px;
    font-weight: bold;
    pointer-events: none;
    opacity: ${(props: CopyIconProps) => (props.copied ? 1 : 0)};
    transition: opacity 0.3s;
  }
`;
