import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import Icon from '../Icon';
import './Toast.scss';
import Button from '../Button';

interface ToasterProps {
  isOpen: boolean;
  variant: 'success' | 'warning' | 'danger' | 'info' | 'confirm';
  toastTitle: string;
  toastMessage?: string;
  onCancelClick?: () => void;
  onConfirmation?: () => void;
  displayDuration?: number;
  confirmationText?: string;
}

const Toaster: React.FC<ToasterProps> = ({
  isOpen = false,
  variant = 'success',
  toastTitle = 'Success',
  onCancelClick = () => {},
  onConfirmation = () => {},
  toastMessage = 'Hello this is child element',
  displayDuration = 5000,
  confirmationText = 'Confirm',
}) => {
  const [isExiting, setIsExiting] = useState(false);
  const iconMap = {
    success: 'success',
    info: 'info',
    warning: 'warning',
    danger: 'error',
    confirm: 'delete',
  };

  const getToasterIcon = (
    variant: 'success' | 'warning' | 'danger' | 'info' | 'confirm'
  ) => {
    const name = iconMap[variant];
    return <Icon name={name} height={40} width={40} />;
  };
  useEffect(() => {
    if (isOpen && variant !== 'confirm') {
      const timer = setTimeout(() => {
        setIsExiting(true);
        setTimeout(onCancelClick, 500); // Duration of exit animation
      }, displayDuration);

      return () => {
        clearTimeout(timer);
        setIsExiting(false);
      };
    }
    return () => {};
  }, [isOpen]);

  const handleClose = () => {
    setIsExiting(true);
    setTimeout(() => {
      onCancelClick();
      setIsExiting(false);
    }, 500);
  };

  if (!isOpen && !isExiting) return null;

  return createPortal(
    <div
      role="alert"
      aria-live="assertive"
      className={`toaster-overlay  ${isExiting ? 'exiting' : ''}`}
    >
      <div
        className={`toaster toaster--bottom-right ${
          isExiting ? 'exiting' : ''
        }`}
      >
        <div className={`toaster-container toaster--${variant}`}>
          {getToasterIcon(variant)}
          <div className="toaster-content">
            <div className="toaster-header-title">{toastTitle}</div>
            <div className="toaster-message">{toastMessage}</div>
            {variant === 'confirm' && (
              <div className="toaster-prompt">
                <Button onClick={handleClose} variant="secondary">
                  Cancel
                </Button>
                <Button onClick={onConfirmation} variant="danger">
                  {confirmationText}
                </Button>
              </div>
            )}
          </div>

          <div className="close-icon-wrapper" onClick={handleClose}>
            <Icon name="close" height={8} width={8} />
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
};

export default Toaster;
