"use client"

import { useMemo } from "react"
import { useQuery } from "convex/react"
import { IconClockHour4, IconMessages, IconTrendingDown, IconTrendingUp } 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 { Badge } from "@/components/ui/badge"
import {
  Card,
  CardAction,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"

function formatMinutes(value: number | null) {
  if (value === null) return "—"
  if (value < 60) return `${Math.round(value)} min`
  const hours = Math.floor(value / 60)
  const minutes = Math.round(value % 60)
  if (minutes === 0) return `${hours}h`
  return `${hours}h ${minutes}min`
}

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

export function SectionCards() {
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

  const dashboard = useQuery(
    api.reports.dashboardOverview,
    convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
  )

  const trendInfo = useMemo(() => {
    if (!dashboard?.newTickets) return { value: null, label: "Aguardando dados", icon: IconTrendingUp }
    const trend = dashboard.newTickets.trendPercentage
    if (trend === null) {
      return { value: null, label: "Sem histórico", icon: IconTrendingUp }
    }
    const positive = trend >= 0
    const icon = positive ? IconTrendingUp : IconTrendingDown
    const label = `${positive ? "+" : ""}${trend.toFixed(1)}%`
    return { value: trend, label, icon }
  }, [dashboard])

  const responseDelta = useMemo(() => {
    if (!dashboard?.firstResponse) return { delta: null, label: "Sem dados", positive: false }
    const delta = dashboard.firstResponse.deltaMinutes
    if (delta === null) return { delta: null, label: "Sem comparação", positive: false }
    const positive = delta <= 0
    const value = `${delta > 0 ? "+" : ""}${Math.round(delta)} min`
    return { delta, label: value, positive }
  }, [dashboard])

  const TrendIcon = trendInfo.icon

  return (
    <div className="grid grid-cols-1 gap-4 px-4 sm:grid-cols-2 xl:grid-cols-4 xl:px-8">
      <Card className="@container/card border border-border/60 bg-gradient-to-br from-white/90 via-white to-primary/5 p-5 shadow-sm">
        <CardHeader className="gap-3">
          <CardDescription>Tickets novos</CardDescription>
          <CardTitle className="text-3xl font-semibold tabular-nums">
            {dashboard ? dashboard.newTickets.last24h : <Skeleton className="h-8 w-20" />}
          </CardTitle>
          <CardAction>
            <Badge
              variant="outline"
              className={`rounded-full gap-1 px-2 py-1 text-xs ${
                trendInfo.value !== null && trendInfo.value < 0 ? "text-red-500" : ""
              }`}
            >
              <TrendIcon className="size-3.5" />
              {trendInfo.label}
            </Badge>
          </CardAction>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1 text-sm text-muted-foreground">
          <div className="flex gap-2 text-foreground">
            {trendInfo.value === null
              ? "Aguardando histórico"
              : trendInfo.value >= 0
                ? "Volume acima do período anterior"
                : "Volume abaixo do período anterior"}
          </div>
          <span>Comparação com as 24h anteriores.</span>
        </CardFooter>
      </Card>

      <Card className="@container/card border border-border/60 bg-gradient-to-br from-white/90 via-white to-primary/5 p-5 shadow-sm">
        <CardHeader className="gap-3">
          <CardDescription>Tempo médio da 1ª resposta</CardDescription>
          <CardTitle className="text-3xl font-semibold tabular-nums">
            {dashboard ? formatMinutes(dashboard.firstResponse.averageMinutes) : <Skeleton className="h-8 w-24" />}
          </CardTitle>
          <CardAction>
            <Badge
              variant="outline"
              className={`rounded-full gap-1 px-2 py-1 text-xs ${
                responseDelta.delta !== null && !responseDelta.positive ? "text-amber-500" : ""
              }`}
            >
              {responseDelta.delta !== null && responseDelta.delta > 0 ? (
                <IconTrendingUp className="size-3.5" />
              ) : (
                <IconTrendingDown className="size-3.5" />
              )}
              {responseDelta.label}
            </Badge>
          </CardAction>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1 text-sm text-muted-foreground">
          <span className="text-foreground">
            {dashboard
              ? `${dashboard.firstResponse.responsesCount} tickets com primeira resposta`
              : "Carregando amostra"}
          </span>
          <span>Média móvel dos últimos 7 dias.</span>
        </CardFooter>
      </Card>

      <Card className="@container/card border border-border/60 bg-gradient-to-br from-white/90 via-white to-primary/5 p-5 shadow-sm">
        <CardHeader className="gap-3">
          <CardDescription>Tickets aguardando ação</CardDescription>
          <CardTitle className="text-3xl font-semibold tabular-nums">
            {dashboard ? dashboard.awaitingAction.total : <Skeleton className="h-8 w-16" />}
          </CardTitle>
          <CardAction>
            <Badge variant="outline" className="rounded-full gap-1 px-2 py-1 text-xs">
              <IconClockHour4 className="size-3.5" />
              {dashboard ? `${dashboard.awaitingAction.atRisk} em risco` : "—"}
            </Badge>
          </CardAction>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1 text-sm text-muted-foreground">
          <span className="text-foreground">Inclui status "Novo", "Aberto" e "Em espera".</span>
          <span>Atrasos calculados com base no prazo de SLA.</span>
        </CardFooter>
      </Card>

      <Card className="@container/card border border-border/60 bg-gradient-to-br from-white/90 via-white to-primary/5 p-5 shadow-sm">
        <CardHeader className="gap-3">
          <CardDescription>CSAT recente</CardDescription>
          <CardTitle className="text-3xl font-semibold tabular-nums">
            {dashboard ? formatScore(dashboard.csat.averageScore) : <Skeleton className="h-8 w-12" />}
          </CardTitle>
          <CardAction>
            <Badge variant="outline" className="rounded-full gap-1 px-2 py-1 text-xs">
              <IconMessages className="size-3.5" />
              {dashboard ? `${dashboard.csat.totalSurveys} pesquisas` : "—"}
            </Badge>
          </CardAction>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1 text-sm text-muted-foreground">
          <span className="text-foreground">Notas de satisfação recebidas nos últimos períodos.</span>
          <span>Escala de 1 a 5 pontos.</span>
        </CardFooter>
      </Card>
    </div>
  )
}
