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;
  dismissible?: boolean;
  onDismiss?: () => void;
}

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

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

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

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

    if (show) classes += ' show';

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

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

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

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

    let dismissTimeout: number;

    if (show) {
      dismissTimeout = setTimeout(() => {
        dismiss();
      }, timer);
    }

    return () => {
      if (dismissTimeout) clearTimeout(dismissTimeout);
    };
  }, [timer, show, 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>
  );
}
