"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 { 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 } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const data = useQuery(
    api.reports.csatOverview,
    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

  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.csv?range=${timeRange}${companyId !== "all" ? `&companyId=${companyId}` : ""}`} download>
                    Exportar CSV
                  </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>
          <ul className="space-y-3">
            {data.distribution.map((entry: { score: number; total: number }) => (
              <li key={entry.score} className="flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3">
                <div className="flex items-center gap-3">
                  <Badge variant="outline" className="rounded-full border-neutral-300 text-neutral-600">
                    Nota {entry.score}
                  </Badge>
                  <span className="text-sm text-neutral-700">{entry.total} respostas</span>
                </div>
                <span className="text-sm font-medium text-neutral-900">
                  {data.totalSurveys === 0 ? "0%" : `${((entry.total / data.totalSurveys) * 100).toFixed(0)}%`}
                </span>
              </li>
            ))}
          </ul>
        </CardContent>
      </Card>
    </div>
  )
}
