"use client"

import { useMemo, useState } from "react"
import { useQuery } from "convex/react"
import { IconInbox, IconAlertTriangle, IconFilter } 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 { Button } from "@/components/ui/button"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"

const PRIORITY_LABELS: Record<string, string> = {
  LOW: "Baixa",
  MEDIUM: "Média",
  HIGH: "Alta",
  URGENT: "Crítica",
}

const STATUS_LABELS: Record<string, string> = {
  PENDING: "Pendentes",
  AWAITING_ATTENDANCE: "Em andamento",
  PAUSED: "Pausados",
  RESOLVED: "Resolvidos",
}

export function BacklogReport() {
  const [timeRange, setTimeRange] = useState("90d")
  const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const data = useQuery(
    api.reports.backlogOverview,
    convexUserId ? { tenantId, viewerId: convexUserId as Id<"users">, range: timeRange, 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 mostCriticalPriority = useMemo(() => {
    if (!data) return null
    const entries = Object.entries(data.priorityCounts) as Array<[string, number]>
    if (entries.length === 0) return null
    return entries.reduce((prev, current) => (current[1] > prev[1] ? current : prev))
  }, [data])

  if (!data) {
    return (
      <div className="space-y-6">
        {Array.from({ length: 3 }).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-3">
        <Card className="border-slate-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
              <IconInbox className="size-4 text-neutral-500" /> Tickets em aberto
            </CardTitle>
            <CardDescription className="text-neutral-600">Backlog total em atendimento.</CardDescription>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">{data.totalOpen}</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" /> Prioridade predominante
            </CardTitle>
            <CardDescription className="text-neutral-600">Volume por prioridade no backlog.</CardDescription>
          </CardHeader>
          <CardContent className="text-xl font-semibold text-neutral-900">
            {mostCriticalPriority ? (
              <span>
                {PRIORITY_LABELS[mostCriticalPriority[0]] ?? mostCriticalPriority[0]} ({mostCriticalPriority[1]})
              </span>
            ) : (
              "—"
            )}
          </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">
              <IconFilter className="size-4 text-neutral-500" /> Status acompanhados
            </CardTitle>
            <CardDescription className="text-neutral-600">Distribuição dos tickets por status.</CardDescription>
          </CardHeader>
          <CardContent className="text-xl font-semibold text-neutral-900">
            {Object.keys(data.statusCounts).length}
          </CardContent>
        </Card>
      </div>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">Status do backlog</CardTitle>
          <CardDescription className="text-neutral-600">
            Acompanhe a evolução dos tickets pelas fases do fluxo de atendimento.
          </CardDescription>
          <CardAction>
            <div className="flex flex-wrap items-center justify-end gap-2 md:gap-3">
              <Select value={companyId} onValueChange={setCompanyId}>
                <SelectTrigger className="hidden w-56 md:flex">
                  <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>

              <ToggleGroup
                type="single"
                value={timeRange}
                onValueChange={setTimeRange}
                variant="outline"
                className="hidden *:data-[slot=toggle-group-item]:!px-4 md:flex"
              >
                <ToggleGroupItem value="90d">90 dias</ToggleGroupItem>
                <ToggleGroupItem value="30d">30 dias</ToggleGroupItem>
                <ToggleGroupItem value="7d">7 dias</ToggleGroupItem>
              </ToggleGroup>

              <Button asChild size="sm" variant="outline">
                <a href={`/api/reports/backlog.csv?range=${timeRange}${companyId !== "all" ? `&companyId=${companyId}` : ""}`} download>
                  Exportar CSV
                </a>
              </Button>
            </div>
          </CardAction>
        </CardHeader>
        <CardContent>
          <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {(Object.entries(data.statusCounts) as Array<[string, number]>).map(([status, total]) => (
              <div key={status} className="rounded-xl border border-slate-200 p-4">
                <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
                  {STATUS_LABELS[status] ?? status}
                </p>
                <p className="mt-2 text-2xl font-semibold text-neutral-900">{total}</p>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">Backlog por prioridade</CardTitle>
          <CardDescription className="text-neutral-600">
            Analise a pressão de atendimento conforme o nível de urgência.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {(Object.entries(data.priorityCounts) as Array<[string, number]>).map(([priority, total]) => (
              <div key={priority} className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3">
                <span className="text-sm font-medium text-neutral-800">
                  {PRIORITY_LABELS[priority] ?? priority}
                </span>
                <Badge variant="outline" className="rounded-full border-neutral-300 text-neutral-600">
                  {total} ticket{total === 1 ? "" : "s"}
                </Badge>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">Filas com maior backlog</CardTitle>
          <CardDescription className="text-neutral-600">
            Identifique onde concentrar esforços de atendimento.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {data.queueCounts.length === 0 ? (
            <p className="rounded-lg border border-dashed border-slate-200 p-6 text-sm text-neutral-500">
              Nenhuma fila com tickets abertos no momento.
            </p>
          ) : (
            <ul className="space-y-3">
            {data.queueCounts.map((queue: { id: string; name: string; total: number }) => (
                <li key={queue.id} className="flex items-center justify-between 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>
                  </div>
                  <Badge variant="outline" className="rounded-full border-neutral-300 text-neutral-600">
                    {queue.total} em aberto
                  </Badge>
                </li>
              ))}
            </ul>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
