"use client"

import { useMemo } from "react"
import { useQuery } from "convex/react"
import { IconAlertTriangle, IconGraph, IconClockHour4 } from "@tabler/icons-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 { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useState } from "react"

function formatMinutes(value: number | null) {
  if (value === null) return "—"
  if (value < 60) return `${value.toFixed(0)} min`
  const hours = Math.floor(value / 60)
  const minutes = Math.round(value % 60)
  if (minutes === 0) return `${hours}h`
  return `${hours}h ${minutes}min`
}

export function SlaReport() {
  const [companyId, setCompanyId] = useState<string>("all")
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const data = useQuery(
    api.reports.slaOverview,
    convexUserId
      ? ({ tenantId, viewerId: convexUserId as Id<"users">, companyId: companyId === "all" ? undefined : (companyId as Id<"companies">) })
      : "skip"
  )
  const companies = useQuery(api.companies.list, convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip") as Array<{ id: Id<"companies">; name: string }> | undefined

  const queueTotal = useMemo(
    () => data?.queueBreakdown.reduce((acc: number, queue: { open: number }) => acc + queue.open, 0) ?? 0,
    [data]
  )

  if (!data) {
    return (
      <div className="space-y-6">
        {Array.from({ length: 4 }).map((_, index) => (
          <Skeleton key={index} className="h-32 rounded-2xl" />
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-8">
      <div className="grid gap-4 md:grid-cols-4">
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Tickets abertos</CardTitle>
            <CardDescription className="text-neutral-600">Chamados ativos acompanhados pelo SLA.</CardDescription>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">{data.totals.open}</CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
              <IconAlertTriangle className="size-4 text-amber-500" /> Vencidos
            </CardTitle>
            <CardDescription className="text-neutral-600">Tickets que ultrapassaram o prazo previsto.</CardDescription>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">{data.totals.overdue}</CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
              <IconClockHour4 className="size-4 text-neutral-500" /> Tempo resposta médio
            </CardTitle>
            <CardDescription className="text-neutral-600">Com base nos tickets respondidos.</CardDescription>
          </CardHeader>
          <CardContent className="text-2xl font-semibold text-neutral-900">
            {formatMinutes(data.response.averageFirstResponseMinutes ?? null)}
            <p className="mt-1 text-xs text-neutral-500">{data.response.responsesRegistered} registros</p>
          </CardContent>
        </Card>
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
              <IconGraph className="size-4 text-neutral-500" /> Tempo resolução médio
            </CardTitle>
            <CardDescription className="text-neutral-600">Chamados finalizados no período analisado.</CardDescription>
          </CardHeader>
          <CardContent className="text-2xl font-semibold text-neutral-900">
            {formatMinutes(data.resolution.averageResolutionMinutes ?? null)}
            <p className="mt-1 text-xs text-neutral-500">{data.resolution.resolvedCount} resolvidos</p>
          </CardContent>
        </Card>
      </div>

      <Card className="border-slate-200">
        <CardHeader>
          <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
            <div>
              <CardTitle className="text-lg font-semibold text-neutral-900">Fila x Volume aberto</CardTitle>
              <CardDescription className="text-neutral-600">
                Distribuição dos {queueTotal} tickets abertos por fila de atendimento.
              </CardDescription>
            </div>
            <CardAction>
              <Select value={companyId} onValueChange={setCompanyId}>
                <SelectTrigger className="w-56">
                  <SelectValue placeholder="Todas as empresas" />
                </SelectTrigger>
                <SelectContent className="rounded-xl">
                  <SelectItem value="all">Todas as empresas</SelectItem>
                  {(companies ?? []).map((c) => (
                    <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Button asChild size="sm" variant="outline">
                <a href={`/api/reports/sla.csv${companyId !== "all" ? `?companyId=${companyId}` : ""}`} download>
                  Exportar CSV
                </a>
              </Button>
            </CardAction>
          </div>
        </CardHeader>
        <CardContent>
          {data.queueBreakdown.length === 0 ? (
            <p className="rounded-lg border border-dashed border-slate-200 p-6 text-sm text-neutral-500">
              Nenhuma fila com tickets ativos no momento.
            </p>
          ) : (
            <ul className="space-y-3">
            {data.queueBreakdown.map((queue: { id: string; name: string; open: number }) => (
                <li key={queue.id} className="flex items-center justify-between gap-4 rounded-xl border border-slate-200 px-4 py-3">
                  <div className="flex flex-col">
                    <span className="text-sm font-medium text-neutral-900">{queue.name}</span>
                    <span className="text-xs text-neutral-500">{((queue.open / Math.max(queueTotal, 1)) * 100).toFixed(0)}% do volume aberto</span>
                  </div>
                  <Badge variant="outline" className="rounded-full border-neutral-300 text-neutral-600">
                    {queue.open} tickets
                  </Badge>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
