import { cva, cx, VariantProps } from 'class-variance-authority';
import { toast as sonnerToast } from 'sonner';

import { IconButton } from '../icon-button';
import { Icon } from '../iconography';
import './toast.css';

const toastStyles = cva('c-toast', {
  variants: {
    type: {
      info: 'c-toast-info',
      error: 'c-toast-error',
      success: 'c-toast-success',
      warning: 'c-toast-warning',
    },
  },
  defaultVariants: {
    type: 'success',
  },
});

type ToastType = 'info' | 'error' | 'success' | 'warning';
type ToastStylesProps = VariantProps<typeof toastStyles>;
export type ToastProps = Omit<React.ComponentProps<'div'>, 'title'> &
  Omit<ToastStylesProps, 'type'> & {
    title: React.ReactNode;
    type?: ToastType;
    message?: React.ReactNode;
    timeout?: number;
  };

const iconMap = {
  info: Icon.Info,
  error: Icon.Error,
  success: Icon.CheckWithCircle,
  warning: Icon.Warning,
};

export const toast = ({ title, message, type = 'success', timeout = 6000 }: ToastProps) => {
  const ToastIcon = iconMap[type];
  const withMessage = !!message;
  const toastId = Date.now().toString();

  sonnerToast.custom(
    id => (
      <div
        data-testid={`toast-${type}`}
        className={cx(toastStyles({ type }), withMessage ? 'c-toast-with-message' : 'c-toast-title-only')}
      >
        <div>{<ToastIcon width={26} height={26} />}</div>
        <div>
          <div className="c-toast-title">{title}</div>
          {!!message && <div className="c-toast-message">{message}</div>}
        </div>
        <div className="c-toast-close">
          <IconButton onClick={() => sonnerToast.dismiss(id)} size="xs">
            <Icon.Cancel width={12} height={12} />
          </IconButton>
        </div>
      </div>
    ),
    {
      id: toastId,
      duration: timeout,
      style: { width: '100%' },
    },
  );

  return toastId;
};

toast.dismiss = sonnerToast.dismiss;
