import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useCallback } from 'react'
import api from '@/services/api'
import type { Notification, NotificationList } from '@/types'

const NOTIFICATIONS_KEY = ['notifications'] as const

async function fetchNotifications(): Promise<NotificationList> {
  const res = await api.get<NotificationList>('/notifications')
  return res.data
}

export function useNotifications() {
  const queryClient = useQueryClient()

  const { data, isLoading } = useQuery({
    queryKey: NOTIFICATIONS_KEY,
    queryFn: fetchNotifications,
    refetchInterval: 60_000,
  })

  const markAsReadMutation = useMutation({
    mutationFn: async (id: number) => {
      await api.put<Notification>(`/notifications/${id}/read`)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: NOTIFICATIONS_KEY })
    },
  })

  const markAllAsReadMutation = useMutation({
    mutationFn: async () => {
      await api.put<{ marked_read: number }>('/notifications/read-all')
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: NOTIFICATIONS_KEY })
    },
  })

  const markAsRead = useCallback(
    (id: number) => {
      markAsReadMutation.mutate(id)
    },
    [markAsReadMutation],
  )

  const markAllAsRead = useCallback(() => {
    markAllAsReadMutation.mutate()
  }, [markAllAsReadMutation])

  const refresh = useCallback(() => {
    queryClient.invalidateQueries({ queryKey: NOTIFICATIONS_KEY })
  }, [queryClient])

  return {
    notifications: data?.items ?? [],
    unreadCount: data?.unread_count ?? 0,
    loading: isLoading,
    markAsRead,
    markAllAsRead,
    refresh,
  }
}
