import { useEffect, useRef } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { jellyfinClient, getItemsApi } from '../api/jellyfin'
import { toast } from '../stores/toast-store'

/**
 * Background poller that checks for newly-added library items and
 * surfaces toast notifications. Stores the most recent `DateCreated`
 * timestamp in localStorage so restarts don't re-notify about old
 * items.
 */
export function useNewReleaseNotifications(enabled: boolean) {
  const qc = useQueryClient()
  const lastNotifiedRef = useRef<string | null>(
    (() => {
      try { return localStorage.getItem('jf_bell_opened') } catch { return null }
    })()
  )

  useEffect(() => {
    if (!enabled) return
    const api = jellyfinClient.getApi()
    if (!api) return
    const apiRef = api

    async function check() {
      try {
        const res = await getItemsApi(apiRef).getItems({
          userId: jellyfinClient.getAuthState()!.userId,
          sortBy: ['DateCreated'],
          sortOrder: ['Descending'],
          limit: 5,
          recursive: true,
          includeItemTypes: ['Movie', 'Series'],
          fields: ['DateCreated'],
        })
        const items = res.data.Items || []
        const newOnes = items.filter(it => {
          const created = it.DateCreated
          if (!created) return false
          if (!lastNotifiedRef.current) return false
          return created > lastNotifiedRef.current
        })
        if (newOnes.length > 0) {
          const first = newOnes[0]
          toast(
            `${newOnes.length} new ${newOnes.length === 1 ? 'item' : 'items'} added - ${first.Name}`,
            'success',
          )
        }
        const newest = items[0]?.DateCreated
        if (newest) {
          lastNotifiedRef.current = newest
          try { localStorage.setItem('jf_bell_opened', newest) } catch { /* noop */ }
        }
        // Refresh the home page recently-added cache
        qc.invalidateQueries({ queryKey: ['jellyfin', 'home', 'recentlyAdded'] })
      } catch { /* ignore */ }
    }

    // First check after a short delay so the app has finished loading
    const first = setTimeout(check, 30_000)
    const interval = setInterval(check, 5 * 60 * 1000)
    return () => {
      clearTimeout(first)
      clearInterval(interval)
    }
  }, [enabled, qc])
}
