"use client"

import { useQuery } from "convex/react"
import { api } from "@/convex/_generated/api"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import type { TicketQueueSummary } from "@/lib/schemas/ticket"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Progress } from "@/components/ui/progress"
import { useAuth } from "@/lib/auth-client"
import type { Id } from "@/convex/_generated/dataModel"

interface TicketQueueSummaryProps {
  queues?: TicketQueueSummary[]
  layout?: "default" | "compact"
}

export function TicketQueueSummaryCards({ queues, layout = "default" }: TicketQueueSummaryProps) {
  const { convexUserId, isStaff } = useAuth()
  const enabled = Boolean(isStaff && convexUserId)
  const shouldFetch = Boolean(!queues && enabled)
  const fromServer = useQuery(
    api.queues.summary,
    shouldFetch ? { tenantId: DEFAULT_TENANT_ID, viewerId: convexUserId as Id<"users"> } : "skip"
  ) as TicketQueueSummary[] | undefined
  const data: TicketQueueSummary[] = queues ?? fromServer ?? []

  const gridLayoutClass =
    layout === "compact"
      ? "mx-auto grid w-full max-w-5xl grid-cols-1 gap-5 pb-3 md:grid-cols-2"
      : "grid w-full grid-cols-1 gap-5 pb-3 sm:grid-cols-2 md:grid-cols-3"

  if (!queues && shouldFetch && fromServer === undefined) {
    return (
      // Usa o mesmo grid do estado carregado para não “pular”
      <div className="h-full min-h-0 overflow-auto">
        <div className={gridLayoutClass}>
          {Array.from({ length: 3 }).map((_, index) => (
            <div key={index} className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
              <div className="h-4 w-24 animate-pulse rounded bg-slate-100" />
              <div className="mt-4 h-3 w-full animate-pulse rounded bg-slate-100" />
            </div>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="h-full min-h-0 overflow-auto">
      {/* Grade responsiva: compacta no modo widget, ampla nos demais contextos */}
      <div className={gridLayoutClass}>
        {data.map((queue, index) => {
          const totalOpen = queue.pending + queue.inProgress + queue.paused
          const breachPercent = totalOpen === 0 ? 0 : Math.round((queue.breached / totalOpen) * 100)
          return (
            <Card
              key={queue.id ?? `${queue.name ?? "queue"}-${index}`}
              className="min-w-0 rounded-2xl border border-slate-200 bg-white p-3.5 shadow-sm sm:p-4"
            >
              <CardHeader className="min-w-0 pb-1.5 sm:pb-2">
                <CardDescription className="text-xs uppercase tracking-wide text-neutral-500">Fila</CardDescription>
                <CardTitle className="min-w-0 line-clamp-2 text-lg font-semibold leading-tight text-neutral-900 sm:text-xl">
                  {queue.name}
                </CardTitle>
              </CardHeader>
              {/* min-w-0 evita conteúdo interno empurrar a coluna */}
              <CardContent className="min-w-0 space-y-3 sm:space-y-4">
                <div className="grid min-w-0 grid-cols-1 gap-2.5 sm:grid-cols-3">
                  <div className="flex min-w-0 flex-col items-start justify-between gap-2 rounded-xl border border-slate-200 bg-gradient-to-br from-white via-white to-slate-100 px-3 py-2.5 text-left shadow-sm lg:px-4 lg:py-3">
                    <p className="min-w-0 pr-0.5 text-[0.68rem] font-semibold uppercase leading-tight tracking-[0.02em] text-neutral-500 sm:text-[0.72rem] lg:text-xs">
                      Pendentes
                    </p>
                    <p className="text-2xl font-bold tracking-tight text-neutral-900 tabular-nums sm:text-3xl">
                      {queue.pending}
                    </p>
                  </div>
                  <div className="flex min-w-0 flex-col items-start justify-between gap-2 rounded-xl border border-sky-200 bg-gradient-to-br from-white via-white to-sky-50 px-3 py-2.5 text-left shadow-sm lg:px-4 lg:py-3">
                    <p className="min-w-0 pr-0.5 text-[0.68rem] font-semibold uppercase leading-tight tracking-[0.02em] text-sky-700 sm:text-[0.72rem] lg:text-xs">
                      Em andamento
                    </p>
                    <p className="text-2xl font-bold tracking-tight text-sky-700 tabular-nums sm:text-3xl">
                      {queue.inProgress}
                    </p>
                  </div>
                  <div className="flex min-w-0 flex-col items-start justify-between gap-2 rounded-xl border border-amber-200 bg-gradient-to-br from-white via-white to-amber-50 px-3 py-2.5 text-left shadow-sm lg:px-4 lg:py-3">
                    <p className="min-w-0 pr-0.5 text-[0.68rem] font-semibold uppercase leading-tight tracking-[0.02em] text-amber-700 sm:text-[0.72rem] lg:text-xs">
                      Pausados
                    </p>
                    <p className="text-2xl font-bold tracking-tight text-amber-700 tabular-nums sm:text-3xl">
                      {queue.paused}
                    </p>
                  </div>
                </div>
                <div className="pt-1">
                  <Progress value={breachPercent} className="h-1.5 bg-slate-100" indicatorClassName="bg-[#00e8ff]" />
                  <span className="mt-2 block text-xs text-neutral-500">
                    {breachPercent}% dos chamados da fila estão fora do SLA
                  </span>
                  <span className="mt-1 block text-xs text-neutral-400">
                    Em atraso: {queue.breached}
                  </span>
                </div>
              </CardContent>
            </Card>
          )
        })}
      </div>
    </div>
  )
}
