import React, { FC, useEffect, useState } from 'react';
import styled from 'styled-components';
import { Grid } from '../Grid';
import { Box, BoxProps } from '../Box';
import { Icon } from '../Icon';
import { LinkButton } from '../LinkButton';
import { Text } from '../Text';
import {
  SvgCloseCircle,
  SvgCheckboxMarkedCircle,
  SvgWarning,
  SvgInfo,
} from '../../assets/images/icons';

const iconMap: any = {
  alert: SvgCloseCircle,
  success: SvgCheckboxMarkedCircle,
  warning: SvgWarning,
  info: SvgInfo,
};

export type Props = {
  variant?: 'alert' | 'warning' | 'success' | 'info';
  details?: string;
  onDismiss?: () => void;
} & BoxProps;

const BarWrapper = styled(Grid)`
  position: fixed;
  top: 15px;
  left: 50%;
  transform: translateX(-50%) translateY(-150%);
  z-index: 9999;
  color: ${({ theme }) => theme.colors.white};
  transition: transform 0.3s;

  &.show {
    transform: translateX(-50%);
  }
`;

export const SnackBar: FC<Props> = ({
  variant = 'info',
  details,
  onDismiss,
  ...boxProps
}) => {
  const [show, setShow] = useState<boolean>(false);

  const defaultBoxProps = {
    bg: variant,
    borderRadius: '3',
    boxShadow: '5',
    p: '4',
    width: '100%',
    maxWidth: 504,
  };

  const dismiss = () => {
    setShow(false);
    if (onDismiss) onDismiss();
  };

  useEffect(() => {
    setShow(!!details);
  }, [details]);

  useEffect(() => {
    let dismissTimout: any;
    if (details) {
      dismissTimout = setTimeout(() => {
        dismiss();
      }, 10000);
    }

    return () => {
      if (dismissTimout) clearTimeout(dismissTimout);
    };
  }, [details, dismiss]);

  return (
    <BarWrapper
      className={show ? 'show' : null}
      gridTemplateColumns="20px 1fr auto"
      {...{ ...defaultBoxProps, ...boxProps }}
    >
      <Icon Asset={iconMap[variant]} width={20} height={20} color="white" />
      <Box>{details}</Box>
      <LinkButton onClick={dismiss}>
        <Text color="white" fontSize="0">
          DISMISS
        </Text>
      </LinkButton>
    </BarWrapper>
  );
};
