import React, { useState, useRef } from 'react';

export const useNotifications = () => {
  const [notification, setNotification] = useState({ open: false, message: '', type: 'info' });
  const notificationTimerRef = useRef(null);

  const showNotification = (message, type = 'info') => {
    // Clear any existing timer first
    if (notificationTimerRef.current) {
      clearTimeout(notificationTimerRef.current);
      notificationTimerRef.current = null;
    }

    // First close any existing notification to trigger a fresh animation
    setNotification(prev => ({
      ...prev,
      open: false
    }));

    // Then set the new notification with a slight delay
    setTimeout(() => {
      setNotification({
        open: true,
        message,
        type
      });

      // Auto-dismiss after 7 seconds
      notificationTimerRef.current = setTimeout(() => {
        handleCloseNotification();
      }, 7000);
    }, 50);
  };

  const handleCloseNotification = () => {
    // Clear any existing timer
    if (notificationTimerRef.current) {
      clearTimeout(notificationTimerRef.current);
      notificationTimerRef.current = null;
    }

    // Hide the notification
    setNotification({
      open: false,
      message: '',
      type: 'info'
    });
  };

  const NotificationComponent = () => (
    <div className="notification-container" style={{
      position: 'fixed',
      bottom: '40px',
      left: '0',
      right: '0',
      zIndex: 10000,
      display: 'flex',
      justifyContent: 'center',
      pointerEvents: 'none', // Let clicks pass through container
      width: '100%'
    }}>
      <div
        className={`messages messages--${notification.type === 'status' ? 'info' : notification.type}`}
        role="alert"
        style={{
          opacity: notification.open ? 1 : 0,
          transform: notification.open ? 'translateY(0)' : 'translateY(20px)',
          transition: 'opacity 0.3s ease-out, transform 0.3s ease-out',
          visibility: notification.open ? 'visible' : 'hidden',
          pointerEvents: notification.open ? 'auto' : 'none', // Only capture clicks when open
          borderWidth: '0 0 0 4px', // Left border only
          maxWidth: '500px',
          width: 'auto',
          margin: '0 auto',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)'
        }}
      >
        <div className="messages__content">
          <span>{notification.message}</span>
          <button
            className="messages__close"
            onClick={() => handleCloseNotification()}
            aria-label="Close"
          >×</button>
        </div>
      </div>
    </div>
  );

  return {
    notification,
    showNotification,
    handleCloseNotification,
    NotificationComponent
  };
};
