"use client"

import Link from "next/link"
import { useMemo } from "react"
import { useQuery } from "convex/react"
import { AlertTriangle, BellRing } from "lucide-react"

import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { useAuth } from "@/lib/auth-client"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { cn } from "@/lib/utils"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import { Button } from "@/components/ui/button"

type AlertEntry = {
  _id: string
  companyName: string
  usagePct: number
  threshold: number
  range: string
  recipients: string[]
  createdAt: number
}

export function DashboardAlertsPanel() {
  const { convexUserId, isAdmin, session } = useAuth()
  const tenantId = session?.user?.tenantId ?? DEFAULT_TENANT_ID
  const enabled = Boolean(convexUserId && isAdmin)
  const alerts = useQuery(
    api.alerts.list,
    enabled
      ? {
          tenantId,
          viewerId: convexUserId as Id<"users">,
          limit: 5,
        }
      : "skip"
  ) as AlertEntry[] | undefined

  const items = useMemo(() => (alerts ?? []).slice(0, 5), [alerts])

  return (
    <Card className="rounded-3xl border border-border/60 shadow-sm">
      <CardHeader className="flex flex-row items-center justify-between gap-4">
        <div>
          <CardTitle className="text-base font-semibold">Alertas automáticos</CardTitle>
          <CardDescription>Últimos avisos disparados para gestores</CardDescription>
        </div>
        {isAdmin ? (
          <Button variant="outline" size="sm" asChild>
            <Link href="/admin/alerts">Configurar alertas</Link>
          </Button>
        ) : null}
      </CardHeader>
      <CardContent className="space-y-3">
        {!enabled ? (
          <div className="flex flex-col items-center gap-3 rounded-2xl border border-dashed border-border/60 bg-muted/40 px-4 py-6 text-center text-sm text-muted-foreground">
            <BellRing className="size-6" />
            <p>Apenas administradores podem visualizar os alertas disparados.</p>
          </div>
        ) : alerts === undefined ? (
          <div className="space-y-2">
            {Array.from({ length: 3 }).map((_, index) => (
              <Skeleton key={`alerts-skeleton-${index}`} className="h-16 w-full rounded-2xl" />
            ))}
          </div>
        ) : items.length === 0 ? (
          <div className="rounded-2xl border border-dashed border-border/60 bg-muted/40 px-4 py-6 text-center text-sm text-muted-foreground">
            Nenhum alerta disparado recentemente. Configure thresholds personalizados para acompanhar consumo de horas e SLAs.
          </div>
        ) : (
          <div className="space-y-2">
            {items.map((entry) => (
              <AlertRow key={entry._id} entry={entry} />
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )
}

function AlertRow({ entry }: { entry: AlertEntry }) {
  const exceeded = entry.usagePct >= entry.threshold
  const severityClass = exceeded ? "text-amber-600 bg-amber-50" : "text-emerald-600 bg-emerald-50"

  return (
    <div className="flex flex-col gap-2 rounded-2xl border border-border/60 bg-white/90 px-4 py-3 shadow-sm">
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          <div className={cn("rounded-full p-1", severityClass)}>
            <AlertTriangle className="size-4" />
          </div>
          <p className="text-sm font-semibold text-neutral-800">{entry.companyName}</p>
        </div>
        <Badge variant="outline" className="rounded-full border-border/60 px-3 py-1 text-xs">{entry.range}</Badge>
      </div>
      <div className="flex flex-wrap items-center gap-3 text-xs text-neutral-500">
        <span>
          Uso {entry.usagePct.toFixed(1)}% • Limite {entry.threshold}%
        </span>
        {entry.recipients.length ? (
          <span className="truncate">
            Destinatários: <strong>{entry.recipients.slice(0, 2).join(", ")}</strong>
            {entry.recipients.length > 2 ? ` +${entry.recipients.length - 2}` : ""}
          </span>
        ) : null}
        <span>
          {new Date(entry.createdAt).toLocaleString("pt-BR", {
            day: "2-digit",
            month: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
          })}
        </span>
      </div>
    </div>
  )
}
