import { useEffect } from 'react';
import { Icon } from '../Icon/Icon';
import { FONT_FAMILY_MONO } from '../../../designTokens';

export const Toast = ({
  message,
  variant = 'info',
  duration = 5000,
  onClose,
  position = 'top-right',
  /** 'viewport' = fixed respecto de la pantalla (comportamiento por defecto). 'parent' = absolute respecto del contenedor padre (el padre debe tener position: relative). */
  attach = 'viewport',
  className = '',
  ...props
}) => {
  useEffect(() => {
    if (duration > 0 && onClose) {
      const timer = setTimeout(() => {
        onClose();
      }, duration);
      return () => clearTimeout(timer);
    }
  }, [duration, onClose]);

  const variantClasses = {
    info: 'bg-blue-50 border-blue-200 text-blue-800',
    success: 'bg-green-50 border-green-200 text-green-800',
    warning: 'bg-yellow-50 border-yellow-200 text-yellow-800',
    danger: 'bg-red-50 border-red-200 text-red-800',
  };

  const iconMap = {
    info: 'InformationCircleIcon',
    success: 'CheckCircleIcon',
    warning: 'ExclamationTriangleIcon',
    danger: 'XCircleIcon',
  };

  const positionClasses = {
    'top-right': 'top-4 right-4',
    'top-left': 'top-4 left-4',
    'top-center': 'top-4 left-1/2 transform -translate-x-1/2',
    'bottom-right': 'bottom-4 right-4',
    'bottom-left': 'bottom-4 left-4',
    'bottom-center': 'bottom-4 left-1/2 transform -translate-x-1/2',
  };

  const isCustomVariant = variant === 'success' || variant === 'danger';
  const customConfig = {
    success: {
      background: '#0A742C',
      borderColor: '#0A742C',
      icon: 'CheckCircleIcon',
    },
    danger: {
      background: '#B30808',
      borderColor: '#B30808',
      icon: 'XCircleIcon',
    },
  };

  const dangerDefaultMessage = 'No se pudo concretar la operación. Intente de nuevo.';
  const successDefaultMessage = 'La operación se concretó exitosamente.';
  const displayMessage =
    variant === 'danger' && (message === undefined || message === '')
      ? dangerDefaultMessage
      : variant === 'success' && (message === undefined || message === '')
        ? successDefaultMessage
        : message;

  return (
    <div
      className={`${attach === 'parent' ? 'absolute' : 'fixed'} ${positionClasses[position]} z-[9999] max-w-sm w-full ${className}`}
      {...props}
    >
      {isCustomVariant ? (
        <div
          style={{
            background: customConfig[variant].background,
            border: `1px solid ${customConfig[variant].borderColor}`,
            borderRadius: '8px',
            boxShadow: '0px 4px 6px -2px #0000001A, 0px 10px 15px -3px #0000001A',
            padding: '12px 16px',
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'flex-start',
            gap: '12px',
          }}
        >
          <div style={{ padding: '3px 0 0 3px', flexShrink: 0 }}>
            <Icon
              name={customConfig[variant].icon}
              variant="24-outline"
              size={28}
              style={{ width: 28, height: 28, strokeWidth: 1.5, color: '#FFFFFF', opacity: 1 }}
            />
          </div>
          <div
            style={{
              flex: 1,
              minWidth: 0,
              maxWidth: '284px',
              minHeight: '48px',
              fontFamily: FONT_FAMILY_MONO,
              fontWeight: 400,
              fontStyle: 'normal',
              fontSize: '16px',
              lineHeight: '24px',
              letterSpacing: '0%',
              color: '#FFFFFF',
              display: 'flex',
              alignItems: 'center',
            }}
          >
            {displayMessage}
          </div>
          {onClose && (
            <button
              onClick={onClose}
              type="button"
              style={{
                marginLeft: 'auto',
                padding: 0,
                border: 'none',
                background: 'transparent',
                cursor: 'pointer',
                opacity: 0.5,
              }}
              onMouseEnter={(e) => { e.currentTarget.style.opacity = '0.75'; }}
              onMouseLeave={(e) => { e.currentTarget.style.opacity = '0.5'; }}
            >
              <Icon name="XMarkIcon" size={20} style={{ width: 20, height: 20, color: '#FFFFFF' }} />
            </button>
          )}
        </div>
      ) : (
        <div
          className={`border rounded-lg shadow-lg p-4 flex items-start ${variantClasses[variant]}`}
        >
          <Icon
            name={iconMap[variant]}
            className="mr-3 h-5 w-5 flex-shrink-0 mt-0.5"
          />
          <div className="flex-1">
            <p className="text-sm font-medium">{message}</p>
          </div>
          {onClose && (
            <button
              onClick={onClose}
              className="ml-4 text-current opacity-50 hover:opacity-75"
            >
              <Icon name="XMarkIcon" className="h-5 w-5" />
            </button>
          )}
        </div>
      )}
    </div>
  );
};

export default Toast;

