"use client"

import { useEffect, useState, useCallback } from "react"
import { useToast } from "@/hooks/use-toast"
import { getAllNotifications, type Documento, type Evento } from "@/lib/notifications"
import { useI18n } from "@/contexts/I18nContext"

interface PeriodicAlertsProps {
  documentos: Documento[]
  eventos: Evento[]
  intervalMinutes?: number 
}

export function PeriodicAlerts({
  documentos,
  eventos,
  intervalMinutes = 30, 
}: PeriodicAlertsProps) {
  const { toast } = useToast()
  const { t } = useI18n()
  const [lastAlertTime, setLastAlertTime] = useState<number | null>(null)

  const showAlert = useCallback(() => {
    const notifications = getAllNotifications(documentos, eventos)
    const count = notifications.length

    if (count === 0) return

    const docCount = notifications.filter((n) => n.tipo === "documento").length
    const eventCount = notifications.filter((n) => n.tipo === "evento").length

    let message = ""
    if (docCount > 0 && eventCount > 0) {
      const docPlural = docCount > 1 ? "s" : ""
      const eventPlural = eventCount > 1 ? "s" : ""
      message = t("notifications.bothUpcoming")
        .replace("{docCount}", docCount.toString())
        .replace("{docPlural}", docPlural)
        .replace("{eventCount}", eventCount.toString())
        .replace("{eventPlural}", eventPlural)
    } else if (docCount > 0) {
      const plural = docCount > 1 ? "s" : ""
      message = t("notifications.documentsUpcoming")
        .replace("{count}", docCount.toString())
        .replace("{plural}", plural)
    } else if (eventCount > 0) {
      const plural = eventCount > 1 ? "s" : ""
      message = t("notifications.eventsUpcoming")
        .replace("{count}", eventCount.toString())
        .replace("{plural}", plural)
    }

    toast({
      title: `🔔 ${t("notifications.title")}`,
      description: message,
      duration: 8000, 
    })

    setLastAlertTime(Date.now())
  }, [documentos, eventos, toast, t])

  useEffect(() => {

    const notifications = getAllNotifications(documentos, eventos)
    if (notifications.length > 0 && lastAlertTime === null) {

      const initialTimeout = setTimeout(() => {
        showAlert()
      }, 5000)
      return () => clearTimeout(initialTimeout)
    }
  }, [documentos, eventos, lastAlertTime, showAlert])

  useEffect(() => {
    if (lastAlertTime === null) return

    const intervalMs = intervalMinutes * 60 * 1000
    const interval = setInterval(() => {
      showAlert()
    }, intervalMs)

    return () => clearInterval(interval)
  }, [lastAlertTime, intervalMinutes, showAlert])

  return null 
}

