import { getToken, onMessage } from 'firebase/messaging';
import { getMessaging, isSupported } from 'firebase/messaging';
import type { Messaging } from 'firebase/messaging';

export interface NotificationPermission {
  permission: NotificationPermissionState;
  granted: boolean;
  denied: boolean;
  default: boolean;
}

/**
 * Service pour gérer les notifications push
 */
export class NotificationService {
  private messaging: Messaging | null = null;
  private messagingSupported = false;

  async initialize() {
    // Vérifier le support du navigateur
    this.messagingSupported = await isSupported();
    
    if (!this.messagingSupported) {
      console.warn('Push notifications not supported in this browser');
      return;
    }

    // Initialiser Firebase Messaging
    this.messaging = getMessaging();
    
    // Écouter les messages foreground
    if (this.messaging) {
      onMessage(this.messaging, (payload) => {
        console.log('Message received:', payload);
        this.showNotification(payload);
      });
    }
  }

  /**
   * Demander la permission pour les notifications
   */
  async requestPermission(): Promise<NotificationPermission> {
    if (!('Notification' in window)) {
      throw new Error('This browser does not support notifications');
    }

    const permission = await Notification.requestPermission();

    return {
      permission,
      granted: permission === 'granted',
      denied: permission === 'denied',
      default: permission === 'default',
    };
  }

  /**
   * Obtenir le token FCM pour l'utilisateur
   */
  async getToken(): Promise<string | null> {
    if (!this.messaging) {
      console.warn('Messaging not initialized');
      return null;
    }

    try {
      const token = await getToken(this.messaging, {
        vapidKey: import.meta.env.VITE_FCM_VAPID_KEY,
      });
      return token;
    } catch (error) {
      console.error('Failed to get token:', error);
      return null;
    }
  }

  /**
   * Afficher une notification
   */
  private showNotification(payload: any) {
    const title = payload.notification?.title || 'Veza';
    const options = {
      body: payload.notification?.body,
      icon: payload.notification?.icon || '/icon-192x192.png',
      badge: '/badge-72x72.png',
      tag: payload.data?.conversation_id || 'default',
      requireInteraction: false,
      silent: false,
    };

    // Afficher la notification
    if ('serviceWorker' in navigator && 'Notification' in window) {
      navigator.serviceWorker.ready.then((registration) => {
        registration.showNotification(title, options);
      });
    }
  }

  /**
   * S'abonner aux notifications pour une conversation
   */
  async subscribeToConversation(conversationId: string) {
    // TODO: Implémenter l'abonnement au backend
    console.log('Subscribing to conversation:', conversationId);
  }

  /**
   * Se désabonner des notifications pour une conversation
   */
  async unsubscribeFromConversation(conversationId: string) {
    // TODO: Implémenter le désabonnement au backend
    console.log('Unsubscribing from conversation:', conversationId);
  }

  /**
   * Afficher une notification locale
   */
  showLocalNotification(title: string, options: NotificationOptions) {
    if (!('Notification' in window)) {
      return;
    }

    if (Notification.permission === 'granted') {
      new Notification(title, options);
    }
  }
}

// Instance singleton
export const notificationService = new NotificationService();

