import React, { useEffect, useMemo, useState } from 'react';
import { theme } from '../../styles/theme';
import { Box, BoxProps } from '../Box';
import { Icon } from '../Icon';
import {
  SvgCloseCircle,
  SvgCheckboxMarkedCircle,
  SvgInformationOutline,
  SvgAlertCircle,
} from '../../assets/images/icons';
import { BarWrapper, DissmissButton, transitionTime } from './styles';

const iconMap = {
  alert: SvgAlertCircle,
  success: SvgCheckboxMarkedCircle,
  warning: SvgCloseCircle,
  info: SvgInformationOutline,
};

const colorMap = {
  alert: theme.colors.warning,
  success: theme.colors.success,
  warning: theme.colors.alert,
  info: theme.colors.brandLighter,
};

export interface SnackbarProps extends BoxProps {
  variant?: 'alert' | 'warning' | 'success' | 'info';
  position?: 'left' | 'right';
  details?: string;
  timer?: number | null;
  show?: boolean;
  dismissible?: boolean;
  onDismiss?: () => void;
}

export function Snackbar({
  variant = 'info',
  position,
  details,
  show,
  timer = 10000,
  dismissible = true,
  onDismiss,
  ...boxProps
}: SnackbarProps) {
  const [isShowing, setIsShowing] = useState(show || false);

  const dismiss = () => {
    setIsShowing(false);

    if (onDismiss) {
      setTimeout(() => onDismiss(), transitionTime);
    }
  };

  const classNames = useMemo(() => {
    let classes = '';

    if (isShowing) classes += ' show';

    if (position === 'left') {
      classes += ' left';
    } else if (position === 'right') {
      classes += ' right';
    }

    return classes;
  }, [isShowing, position]);

  useEffect(() => {
    setIsShowing(show === undefined ? Boolean(details) : show);
  }, [show, details]);

  useEffect(() => {
    if (timer === null) return;

    let dismissTimeout: number;

    if (isShowing) {
      dismissTimeout = window.setTimeout(() => dismiss(), timer);
    }

    return () => {
      if (dismissTimeout) clearTimeout(dismissTimeout);
    };
  }, [timer, isShowing, dismiss]);

  return (
    <BarWrapper className={classNames} {...boxProps}>
      <Icon
        Asset={iconMap[variant]}
        color={colorMap[variant]}
        width={20}
        height={20}
      />
      <Box>{details}</Box>

      {dismissible && (
        <DissmissButton onClick={dismiss}>Dismiss</DissmissButton>
      )}
    </BarWrapper>
  );
}
