// Alerts page: unacknowledged + acknowledged alerts with ack action.

import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query'
import { format } from 'date-fns'
import { AlertCircle, Bell, CheckCircle2 } from 'lucide-react'
import { api } from '../lib/api'
import { Button, Card, FadeIn, Pill, Skeleton } from '../components/ui'

export function AlertsPage() {
  const qc = useQueryClient()
  const { data, isLoading } = useQuery({
    queryKey: ['alerts', 'all'],
    queryFn: () => api.alerts({ limit: 100 }),
    refetchInterval: 15_000,
  })

  const ack = useMutation({
    mutationFn: (id: number) => api.acknowledgeAlert(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['alerts'] }),
  })

  const alerts = data?.alerts ?? []
  const unack = alerts.filter((a) => !a.acknowledged_at)
  const acked = alerts.filter((a) => a.acknowledged_at)

  return (
    <div className="flex flex-col gap-8">
      <FadeIn>
        <h1 className="text-h1 mb-2">Alerts</h1>
        <p className="text-body-lg text-ink-400">{unack.length} unacknowledged</p>
      </FadeIn>

      {isLoading && (
        <div className="flex flex-col gap-2">
          {Array.from({ length: 3 }).map((_, i) => <Skeleton key={i} className="h-16" />)}
        </div>
      )}

      {unack.length > 0 && (
        <FadeIn delay={0.05}>
          <h2 className="text-h3 mb-3">Unacknowledged</h2>
          <div className="flex flex-col gap-2">
            {unack.map((a) => (
              <Card key={a.id} padding="md">
                <div className="flex items-center gap-3">
                  <AlertCircle className="w-5 h-5 text-amber-400 shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="text-body text-ink-100">{a.message}</div>
                    <div className="text-caption text-ink-500 mt-0.5">
                      {a.router_id} · {format(new Date(a.created_at), 'MMM d HH:mm:ss')}
                    </div>
                  </div>
                  <Button size="sm" variant="secondary" onClick={() => ack.mutate(a.id)}>
                    <CheckCircle2 className="w-3.5 h-3.5" />
                    Ack
                  </Button>
                </div>
              </Card>
            ))}
          </div>
        </FadeIn>
      )}

      {!isLoading && unack.length === 0 && (
        <Card padding="lg" className="text-center">
          <Bell className="w-10 h-10 mx-auto mb-3 text-ink-500" />
          <p className="text-body text-ink-300">All clear</p>
          <p className="text-caption text-ink-500 mt-1">No unacknowledged alerts</p>
        </Card>
      )}

      {acked.length > 0 && (
        <FadeIn delay={0.1}>
          <h2 className="text-h3 mb-3 mt-6">Acknowledged</h2>
          <div className="flex flex-col gap-1.5">
            {acked.map((a) => (
              <Card key={a.id} padding="sm" className="opacity-60">
                <div className="flex items-center gap-3 px-2 py-1">
                  <Pill tone="success">resolved</Pill>
                  <div className="flex-1 min-w-0 text-caption text-ink-500 truncate">{a.message}</div>
                  <span className="text-[10px] text-ink-600 shrink-0">
                    {a.acknowledged_at && format(new Date(a.acknowledged_at), 'MMM d HH:mm')}
                  </span>
                </div>
              </Card>
            ))}
          </div>
        </FadeIn>
      )}
    </div>
  )
}
