/**
 * Simple toast notification component.
 *
 * @package GetMD
 * @since   1.0.2
 */

import * as React from 'react';
import { Alert, AlertDescription } from './alert';

export interface ToastProps {
  message: string;
  variant?: 'default' | 'destructive';
  onClose?: () => void;
  duration?: number;
}

/**
 * Toast notification component that auto-dismisses after a duration.
 *
 * @param props Toast properties including message, variant, onClose callback, and duration
 * @returns Toast notification as JSX element
 */
export function Toast({ message, variant = 'default', onClose, duration = 3000 }: ToastProps) {
  // Auto-dismiss timer
  React.useEffect(() => {
    if (duration > 0) {
      const timer = setTimeout(() => {
        onClose?.();
      }, duration);

      return () => clearTimeout(timer);
    }
  }, [duration, onClose]);

  // Keyboard escape handler
  React.useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && onClose) {
        onClose();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [onClose]);

  return (
    <div
      className="smx-fixed smx-top-4 smx-right-4 smx-z-50 smx-max-w-md smx-animate-pulse"
      role={variant === 'destructive' ? 'alert' : 'status'}
      aria-live={variant === 'destructive' ? 'assertive' : 'polite'}
      aria-atomic="true"
    >
      <Alert variant={variant} className="smx-shadow-lg">
        <AlertDescription className="smx-flex smx-items-center smx-gap-3">
          {variant === 'default' && (
            <svg aria-hidden="true" className="smx-h-5 smx-w-5 smx-text-green-600 smx-flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          )}
          {variant === 'destructive' && (
            <svg aria-hidden="true" className="smx-h-5 smx-w-5 smx-flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          )}
          <span className="smx-text-sm smx-font-medium smx-flex-1">{message}</span>
          {onClose && (
            <button
              type="button"
              onClick={onClose}
              className="smx-text-gray-400 hover:smx-text-gray-600 smx-transition-colors"
              aria-label="Close notification"
            >
              <svg aria-hidden="true" className="smx-h-4 smx-w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          )}
        </AlertDescription>
      </Alert>
    </div>
  );
}
