'use client'

import { useMemo, useCallback } from 'react'
import { useFinanzasStore } from '@/lib/store'
import { generateAlerts, GenerateAlertsParams } from '@/lib/alerts'

export function useAlerts() {
  const alerts = useFinanzasStore((state) => state.alerts)
  const addAlert = useFinanzasStore((state) => state.addAlert)
  const clearAllAlerts = useFinanzasStore((state) => state.clearAllAlerts)

  const fixedDebts = useFinanzasStore((state) => state.fixedDebts)
  const variableDebts = useFinanzasStore((state) => state.variableDebts)
  const creditCards = useFinanzasStore((state) => state.creditCards)
  const monthlyBudgets = useFinanzasStore((state) => state.monthlyBudgets)
  const currentMonth = useFinanzasStore((state) => state.currentMonth)
  const currentYear = useFinanzasStore((state) => state.currentYear)

  const unreadAlerts = useMemo(
    () => alerts.filter((alert) => !alert.isRead),
    [alerts]
  )

  const unreadCount = unreadAlerts.length

  const regenerateAlerts = useCallback(() => {
    const params: GenerateAlertsParams = {
      fixedDebts,
      variableDebts,
      creditCards,
      monthlyBudgets,
      currentMonth,
      currentYear,
    }

    const newAlerts = generateAlerts(params)

    // Clear existing alerts and add new ones
    clearAllAlerts()

    newAlerts.forEach((alertDraft) => {
      addAlert({ ...alertDraft, isRead: false })
    })

    return newAlerts.length
  }, [
    fixedDebts,
    variableDebts,
    creditCards,
    monthlyBudgets,
    currentMonth,
    currentYear,
    clearAllAlerts,
    addAlert,
  ])

  const dismissAll = useCallback(() => {
    clearAllAlerts()
  }, [clearAllAlerts])

  return {
    alerts,
    unreadCount,
    unreadAlerts,
    regenerateAlerts,
    dismissAll,
  }
}
