"use client"

import * as React from "react"
import { Pie, PieChart, LabelList, Bar, BarChart, CartesianGrid, XAxis } from "recharts"
import { useQuery } from "convex/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 { usePersistentCompanyFilter } from "@/lib/use-company-filter"
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardAction } from "@/components/ui/card"
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Skeleton } from "@/components/ui/skeleton"

export function ViewsCharts() {
  return (
    <div className="grid gap-6 lg:grid-cols-2">
      <BacklogPriorityPie />
      <QueuesOpenBar />
    </div>
  )
}

function BacklogPriorityPie() {
  const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
  const [timeRange, setTimeRange] = React.useState("30d")
  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"
  ) as { priorityCounts: Record<string, number> } | undefined
  const companies = useQuery(api.companies.list, convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip") as Array<{ id: Id<"companies">; name: string }> | undefined

  if (!data) return <Skeleton className="h-[300px] w-full" />
  const PRIORITY_LABELS: Record<string, string> = { LOW: "Baixa", MEDIUM: "Média", HIGH: "Alta", URGENT: "Crítica" }
  const keys = ["LOW", "MEDIUM", "HIGH", "URGENT"]
  const fills = {
    LOW: "var(--chart-1)",
    MEDIUM: "var(--chart-2)",
    HIGH: "var(--chart-3)",
    URGENT: "var(--chart-4)",
  } as const
  const chartData = keys
    .map((k) => ({ name: PRIORITY_LABELS[k] ?? k, value: data.priorityCounts?.[k] ?? 0, fill: fills[k as keyof typeof fills] }))
    .filter((d) => d.value > 0)
  const chartConfig: any = { value: { label: "Tickets" } }

  return (
    <Card className="flex flex-col">
      <CardHeader className="pb-0">
        <CardTitle>Backlog por prioridade</CardTitle>
        <CardDescription>Distribuição de tickets no período</CardDescription>
        <CardAction>
          <div className="flex flex-wrap items-center justify-end gap-2 md:gap-3">
            <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>
            <Select value={timeRange} onValueChange={setTimeRange}>
              <SelectTrigger className="w-40">
                <SelectValue placeholder="Período" />
              </SelectTrigger>
              <SelectContent className="rounded-xl">
                <SelectItem value="90d">Últimos 90 dias</SelectItem>
                <SelectItem value="30d">Últimos 30 dias</SelectItem>
                <SelectItem value="7d">Últimos 7 dias</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardAction>
      </CardHeader>
      <CardContent className="flex-1 pb-0">
        {chartData.length === 0 ? (
          <div className="flex h-[250px] items-center justify-center rounded-xl border border-dashed border-border/60 text-sm text-muted-foreground">
            Sem dados no período selecionado.
          </div>
        ) : (
          <ChartContainer
            config={chartConfig}
            className="mx-auto aspect-square max-h-[250px] [&_.recharts-text]:fill-background"
          >
            <PieChart>
              <ChartTooltip content={<ChartTooltipContent nameKey="value" hideLabel />} />
              <Pie data={chartData} dataKey="value" nameKey="name">
                <LabelList dataKey="name" className="fill-background" stroke="none" fontSize={12} />
              </Pie>
            </PieChart>
          </ChartContainer>
        )}
      </CardContent>
    </Card>
  )
}

function QueuesOpenBar() {
  const [companyId, setCompanyId] = usePersistentCompanyFilter("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"
  ) as { queueBreakdown: { id: string; name: string; open: number }[] } | undefined
  const companies = useQuery(api.companies.list, convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip") as Array<{ id: Id<"companies">; name: string }> | undefined

  if (!data) return <Skeleton className="h-[300px] w-full" />
  const chartData = (data.queueBreakdown ?? []).map((q) => ({ queue: q.name, open: q.open }))
  const chartConfig: any = { open: { label: "Abertos" } }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Filas com maior volume aberto</CardTitle>
        <CardDescription>Distribuição atual por fila</CardDescription>
        <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>
        </CardAction>
      </CardHeader>
      <CardContent>
        {chartData.length === 0 ? (
          <div className="flex h-[250px] items-center justify-center rounded-xl border border-dashed border-border/60 text-sm text-muted-foreground">
            Sem filas com tickets abertos.
          </div>
        ) : (
          <ChartContainer config={chartConfig} className="aspect-auto h-[250px] w-full">
            <BarChart accessibilityLayer data={chartData} margin={{ left: 12, right: 12 }}>
              <CartesianGrid vertical={false} />
              <XAxis dataKey="queue" tickLine={false} axisLine={false} tickMargin={8} minTickGap={32} />
              <ChartTooltip content={<ChartTooltipContent nameKey="open" hideLabel />} />
              <Bar dataKey="open" radius={6} />
            </BarChart>
          </ChartContainer>
        )}
      </CardContent>
    </Card>
  )
}
