import React, { useMemo } from 'react';
import { ToastConfig, ToastType } from '@wix/bex-core';
import {
  FloatingNotification,
  FloatingNotificationType,
  IconElement,
} from '@wix/design-system';
import { InfoCircle, StatusComplete } from '@wix/wix-ui-icons-common';

interface ManageTagsNotificationProps {
  toastConfig: ToastConfig;
  onClose: (toastConfig: ToastConfig) => unknown;
  dataHook?: string;
}

const toastTypeToNotificationType: {
  [key in ToastType]?: FloatingNotificationType;
} = {
  SUCCESS: 'success',
  ERROR: 'destructive',
};

const convertToastConfigToButtonProps = ({
  toastConfig,
  onClose,
}: {
  toastConfig: ToastConfig;
  onClose: (toastConfig: ToastConfig) => unknown;
}) => {
  return {
    label: toastConfig.action?.text,
    onClick: () => {
      toastConfig.action?.onClick?.();

      if (toastConfig.action?.removeToastOnClick) {
        onClose(toastConfig);
      }
    },
  };
};

const toastTypeToIcon: {
  [key in ToastType]?: IconElement;
} = {
  SUCCESS: <StatusComplete />,
  ERROR: <InfoCircle />,
};

export const ManageTagsNotification = ({
  toastConfig,
  onClose,
  dataHook,
}: ManageTagsNotificationProps) => {
  const notificationProps = useMemo(() => {
    let type;
    let prefixIcon;
    if (toastConfig.type) {
      type = toastTypeToNotificationType[toastConfig.type];
      prefixIcon = toastTypeToIcon[toastConfig.type];
    }

    const buttonProps = convertToastConfigToButtonProps({
      toastConfig,
      onClose,
    });

    return {
      type,
      prefixIcon,
      text: toastConfig.message,
      buttonProps:
        toastConfig.action?.uiType === 'BUTTON' ? buttonProps : undefined,
      textButtonProps:
        toastConfig.action?.uiType === 'LINK' ? buttonProps : undefined,
      onClose: () => onClose(toastConfig),
    };
  }, [toastConfig, onClose]);

  return <FloatingNotification dataHook={dataHook} {...notificationProps} />;
};
