/**
 * Hook pour gérer les notifications de playlists
 * T0508: Create Playlist Notifications
 *
 * Ce hook permet d'écouter les notifications liées aux playlists :
 * - Collaborator ajouté
 * - Track ajouté
 * - Playlist partagée
 * - Playlist mise à jour
 */

import { useEffect, useState, useCallback } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/services/api/client';
import { useToast } from '@/hooks/useToast';
import { logger } from '@/utils/logger';

export interface PlaylistNotification {
  id: string;
  user_id: string;
  type:
    | 'playlist_collaborator_added'
    | 'playlist_track_added'
    | 'playlist_shared'
    | 'playlist_updated';
  title: string;
  content: string;
  link?: string;
  read: boolean;
  created_at: string;
}

export interface UsePlaylistNotificationsOptions {
  /**
   * Active ou désactive l'écoute des notifications
   * @default true
   */
  enabled?: boolean;

  /**
   * Intervalle de polling en millisecondes pour vérifier les nouvelles notifications
   * @default 30000 (30 secondes)
   */
  pollInterval?: number;

  /**
   * Callback appelé lorsqu'une nouvelle notification est reçue
   */
  onNotification?: (notification: PlaylistNotification) => void;

  /**
   * Afficher automatiquement les notifications via toast
   * @default true
   */
  showToasts?: boolean;
}

/**
 * Hook pour gérer les notifications de playlists
 */
export function usePlaylistNotifications(
  options: UsePlaylistNotificationsOptions = {},
) {
  const {
    enabled = true,
    pollInterval = 30000,
    onNotification,
    showToasts = true,
  } = options;

  const queryClient = useQueryClient();
  const { toast } = useToast();
  // FE-TYPE-001: IDs are strings (UUIDs), not numbers
  const [lastNotificationId, setLastNotificationId] = useState<string | null>(
    null,
  );

  // Récupérer les notifications
  const { data: notifications, refetch } = useQuery<PlaylistNotification[]>({
    queryKey: ['playlist-notifications'],
    queryFn: async () => {
      const response = await apiClient.get<PlaylistNotification[]>(
        '/api/v1/notifications',
        {
          params: {
            type: 'playlist',
            read: false,
          },
        },
      );
      return response.data;
    },
    enabled,
    refetchInterval: enabled ? pollInterval : false,
    staleTime: 10000, // 10 secondes
  });

  // Filtrer les notifications de playlists
  const playlistNotifications =
    notifications?.filter(
      (n) =>
        n.type === 'playlist_collaborator_added' ||
        n.type === 'playlist_track_added' ||
        n.type === 'playlist_shared' ||
        n.type === 'playlist_updated',
    ) || [];

  // Détecter les nouvelles notifications
  useEffect(() => {
    if (!playlistNotifications.length || !enabled) return;

    // Trouver la notification la plus récente
    const latestNotification = playlistNotifications[0];

    // Si c'est une nouvelle notification (pas encore vue)
    // FE-TYPE-001: Compare IDs as strings
    if (
      lastNotificationId === null ||
      latestNotification.id !== lastNotificationId
    ) {
      setLastNotificationId(latestNotification.id);

      // Appeler le callback
      if (onNotification) {
        onNotification(latestNotification);
      }

      // Afficher un toast si activé
      if (showToasts) {
        const toastConfig = getToastConfig(latestNotification);
        if (toastConfig) {
          toast({
            title: toastConfig.title,
            description: toastConfig.description,
            ...toastConfig.options,
          });
        }
      }
    }
  }, [
    playlistNotifications,
    lastNotificationId,
    enabled,
    onNotification,
    showToasts,
    toast,
  ]);

  // Marquer une notification comme lue
  const markAsRead = useCallback(
    async (notificationId: number) => {
      try {
        await apiClient.post(`/api/v1/notifications/${notificationId}/read`);
        queryClient.invalidateQueries({ queryKey: ['playlist-notifications'] });
      } catch (error) {
        logger.error('Failed to mark notification as read:', { error });
      }
    },
    [queryClient],
  );

  // Marquer toutes les notifications comme lues
  const markAllAsRead = useCallback(async () => {
    try {
      await apiClient.post('/api/v1/notifications/read-all');
      queryClient.invalidateQueries({ queryKey: ['playlist-notifications'] });
    } catch (error) {
      logger.error('Failed to mark all notifications as read:', { error });
    }
  }, [queryClient]);

  // Obtenir le nombre de notifications non lues
  const unreadCount = playlistNotifications.filter((n) => !n.read).length;

  return {
    notifications: playlistNotifications,
    unreadCount,
    markAsRead,
    markAllAsRead,
    refetch,
    isLoading: false,
  };
}

/**
 * Obtient la configuration du toast pour une notification
 */
function getToastConfig(notification: PlaylistNotification): {
  title: string;
  description: string;
  options?: any;
} | null {
  switch (notification.type) {
    case 'playlist_collaborator_added':
      return {
        title: notification.title,
        description: notification.content,
        options: {
          action: notification.link
            ? {
                label: 'Voir',
                onClick: () => {
                  window.location.href = notification.link!;
                },
              }
            : undefined,
        },
      };

    case 'playlist_track_added':
      return {
        title: notification.title,
        description: notification.content,
        options: {
          action: notification.link
            ? {
                label: 'Voir',
                onClick: () => {
                  window.location.href = notification.link!;
                },
              }
            : undefined,
        },
      };

    case 'playlist_shared':
      return {
        title: notification.title,
        description: notification.content,
        options: {
          action: notification.link
            ? {
                label: 'Voir',
                onClick: () => {
                  window.location.href = notification.link!;
                },
              }
            : undefined,
        },
      };

    case 'playlist_updated':
      return {
        title: notification.title,
        description: notification.content,
        options: {
          action: notification.link
            ? {
                label: 'Voir',
                onClick: () => {
                  window.location.href = notification.link!;
                },
              }
            : undefined,
        },
      };

    default:
      return null;
  }
}

export default usePlaylistNotifications;
