'use client'

import { useMemo } from 'react'
import AlertsSection from '@/components/alerts/AlertsSection'
import type { AlertCardData } from '@/components/alerts/AlertCard'
import { trpc } from '@/lib/trpc-client'

export default function AlertsPage() {
  const utils = trpc.useUtils()

  const alertsQuery = trpc.alertas.list.useQuery(
    { page: 1, limit: 100 },
    { refetchOnWindowFocus: false }
  )

  const acknowledgeMutation = trpc.alertas.reconocer.useMutation({
    onSuccess: () => {
      utils.alertas.list.invalidate()
      utils.alertas.conteoActivas.invalidate()
      utils.clientes.dashboardStats.invalidate()
    },
  })
  const resolveMutation = trpc.alertas.resolver.useMutation({
    onSuccess: () => {
      utils.alertas.list.invalidate()
      utils.alertas.conteoActivas.invalidate()
      utils.clientes.dashboardStats.invalidate()
    },
  })

  const alerts: AlertCardData[] = useMemo(() => {
    const list = alertsQuery.data?.alertas ?? []
    return list.map((a) => ({
      id: a.id,
      title: a.titulo,
      device: a.dispositivo?.nombre ?? '—',
      description: a.mensaje,
      severity: a.severidad,
      timestamp: a.createdAt instanceof Date ? a.createdAt : new Date(a.createdAt),
      status: a.estado,
    }))
  }, [alertsQuery.data])

  const handleAcknowledge = (id: string) => {
    acknowledgeMutation.mutate({ id })
  }
  const handleResolve = (id: string) => {
    resolveMutation.mutate({ id })
  }

  return (
    <div className="min-h-full">
      <AlertsSection
        alerts={alerts}
        isLoading={alertsQuery.isLoading}
        onAcknowledge={handleAcknowledge}
        onResolve={handleResolve}
      />
    </div>
  )
}
