import React, { useMemo } from 'react';
import { ToastConfig, ToastType } from '@wix/bex-core';
import { StatusToast } from '@wix/design-system';

const TOAST_TYPE_TO_STATUS: {
  [key in ToastType]?: 'success' | 'error' | 'warning' | 'info';
} = {
  STANDARD: 'info',
  PREMIUM: 'info',
  SUCCESS: 'success',
  WARNING: 'warning',
  ERROR: 'error',
};

interface StatusToastFromConfigProps {
  config: ToastConfig;
  onClose: () => void;
  dataHook?: string;
  messageDataHook?: string;
  actionDataHook?: string;
}

export const StatusToastFromConfig = ({
  config,
  onClose,
  dataHook,
  messageDataHook,
  actionDataHook,
}: StatusToastFromConfigProps) => {
  const action = useMemo(() => {
    if (!config.action?.text) {
      return undefined;
    }
    const handleClick = () => {
      config.action?.onClick?.();
      if (config.action?.removeToastOnClick) {
        onClose();
      }
    };
    return (
      <StatusToast.Action dataHook={actionDataHook} onClick={handleClick}>
        {config.action.text}
      </StatusToast.Action>
    );
  }, [config, onClose, actionDataHook]);

  return (
    <StatusToast
      key={config.biName ?? config.message}
      dataHook={dataHook}
      status={TOAST_TYPE_TO_STATUS[config.type ?? 'STANDARD']}
      dismissible
      onDismiss={onClose}
      action={action}
    >
      {messageDataHook ? (
        <span data-hook={messageDataHook}>{config.message}</span>
      ) : (
        config.message
      )}
    </StatusToast>
  );
};
