import { useEffect, useState } from 'react';
import Pusher from 'pusher-js';
import { useSettings } from './use-settings';
import { useAuth } from './use-auth';

interface Notification {
  title: string;
  message: string;
  type: 'info' | 'success' | 'warning' | 'error';
  timestamp: string;
}

export function useNotifications() {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const { settings } = useSettings();
  const { user } = useAuth();

  useEffect(() => {
    if (!user || !settings?.pusherKey || !settings?.pusherCluster) {
      return;
    }

    // Initialize Pusher
    const pusher = new Pusher(settings.pusherKey, {
      cluster: settings.pusherCluster
    });

    // Create a unique channel name for this user
    const channelName = `user-${user.id}-notifications`;

    // Register the notification channel with the server
    fetch('/api/notifications/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userId: user.id, channelName })
    }).catch(console.error);

    // Subscribe to the notification channel
    const channel = pusher.subscribe(channelName);

    // Handle notifications
    channel.bind('notification', (data: Notification) => {
      setNotifications(prev => [...prev, data]);
    });

    // Cleanup
    return () => {
      channel.unbind_all();
      channel.unsubscribe();
      
      // Unregister the notification channel
      fetch('/api/notifications/unregister', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ channelName })
      }).catch(console.error);

      pusher.disconnect();
    };
  }, [user, settings]);

  return { notifications };
}

// Example usage in a component:
/*
function NotificationComponent() {
  const { notifications } = useNotifications();

  return (
    <div>
      {notifications.map((notification, index) => (
        <div key={index} className={`notification ${notification.type}`}>
          <h4>{notification.title}</h4>
          <p>{notification.message}</p>
          <small>{new Date(notification.timestamp).toLocaleString()}</small>
        </div>
      ))}
    </div>
  );
}
*/
