"use client"

import { useQuery } from "convex/react"
import { IconMoodSmile, IconStars, IconMessageCircle2 } 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 { useState } from "react"
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts"
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { usePersistentCompanyFilter } from "@/lib/use-company-filter"

function formatScore(value: number | null) {
  if (value === null) return "—"
  return value.toFixed(2)
}

export function CsatReport() {
  const [companyId, setCompanyId] = usePersistentCompanyFilter("all")
  const [timeRange, setTimeRange] = useState<string>("90d")
  const { session, convexUserId, isStaff } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const enabled = Boolean(isStaff && convexUserId)
  const data = useQuery(
    api.reports.csatOverview,
    enabled
      ? ({ tenantId, viewerId: convexUserId as Id<"users">, range: timeRange, companyId: companyId === "all" ? undefined : (companyId as Id<"companies">) })
      : "skip"
  )
  const companies = useQuery(api.companies.list, enabled ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip") as Array<{ id: Id<"companies">; name: string }> | undefined

  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">
            <IconMoodSmile className="size-4 text-teal-500" /> CSAT médio
          </CardTitle>
          <CardDescription className="text-neutral-600">Média das respostas recebidas.</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>

                <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/csat.xlsx?range=${timeRange}${companyId !== "all" ? `&companyId=${companyId}` : ""}`} download>
                    Exportar XLSX
                  </a>
                </Button>
              </div>
            </CardAction>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">
            {formatScore(data.averageScore)}
          </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">
              <IconStars className="size-4 text-violet-500" /> Total de respostas
            </CardTitle>
            <CardDescription className="text-neutral-600">Avaliações coletadas nos tickets.</CardDescription>
          </CardHeader>
          <CardContent className="text-3xl font-semibold text-neutral-900">{data.totalSurveys}</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">
              <IconMessageCircle2 className="size-4 text-sky-500" /> Últimas avaliações
            </CardTitle>
            <CardDescription className="text-neutral-600">Até 10 registros mais recentes.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-2">
            {data.recent.length === 0 ? (
              <p className="text-sm text-neutral-500">Ainda não coletamos nenhuma avaliação.</p>
            ) : (
              data.recent.map((item: { ticketId: string; reference: number; score: number; receivedAt: number }) => (
                <div key={`${item.ticketId}-${item.receivedAt}`} className="flex items-center justify-between rounded-lg border border-slate-200 px-3 py-2 text-sm">
                  <span>#{item.reference}</span>
                  <Badge variant="outline" className="rounded-full border-neutral-300 text-neutral-600">
                    Nota {item.score}
                  </Badge>
                </div>
              ))
            )}
          </CardContent>
        </Card>
      </div>

      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">Distribuição das notas</CardTitle>
          <CardDescription className="text-neutral-600">
            Frequência de respostas para cada valor na escala de 1 a 5.
          </CardDescription>
        </CardHeader>
        <CardContent>
          {data.totalSurveys === 0 ? (
            <p className="rounded-lg border border-dashed border-slate-200 p-6 text-sm text-neutral-500">Sem respostas no período.</p>
          ) : (
            <ChartContainer config={{}} className="aspect-auto h-[260px] w-full">
              <BarChart data={data.distribution.map((d: { score: number; total: number }) => ({ score: `Nota ${d.score}`, total: d.total }))}>
                <CartesianGrid vertical={false} />
                <XAxis dataKey="score" tickLine={false} axisLine={false} tickMargin={8} />
                <Bar dataKey="total" fill="var(--chart-3)" radius={[4, 4, 0, 0]} />
                <ChartTooltip content={<ChartTooltipContent className="w-[180px]" nameKey="Respostas" />} />
              </BarChart>
            </ChartContainer>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
