"use client"

import { useQuery } from "convex/react"
import { IconMoodSmile, IconStars, IconMessageCircle2 } from "@tabler/icons-react"
// @ts-expect-error Convex runtime API lacks TypeScript declarations
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, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"

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

export function CsatReport() {
  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"> } : "skip"
  )

  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>
          </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) => (
                <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) => (
              <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>
  )
}
