"use client"

import { useMemo } from "react"
import { useQuery } from "convex/react"
import { IconClockHour4, 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 { cn } from "@/lib/utils"
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`
}

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

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

  const inProgressSummary = useMemo(() => {
    if (dashboard?.inProgress) {
      return dashboard.inProgress
    }
    if (dashboard?.newTickets) {
      return {
        current: dashboard.newTickets.last24h,
        previousSnapshot: dashboard.newTickets.previous24h,
        trendPercentage: dashboard.newTickets.trendPercentage,
      }
    }
    return null
  }, [dashboard])

  const trendInfo = useMemo(() => {
    if (!inProgressSummary) return { value: null, label: "Aguardando dados", icon: IconTrendingUp }
    const trend = inProgressSummary.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 }
  }, [inProgressSummary])

  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

  const resolutionInfo = useMemo(() => {
    if (!dashboard?.resolution) {
      return {
        positive: true,
        badgeLabel: "Sem histórico",
        rateLabel: "Taxa indisponível",
      }
    }
    const current = dashboard.resolution.resolvedLast7d ?? 0
    const previous = dashboard.resolution.previousResolved ?? 0
    const deltaPercentage = dashboard.resolution.deltaPercentage ?? null
    const positive = deltaPercentage !== null ? deltaPercentage >= 0 : current >= previous
    const badgeLabel = deltaPercentage !== null
      ? `${deltaPercentage >= 0 ? "+" : ""}${deltaPercentage.toFixed(1)}%`
      : previous > 0
        ? `${current - previous >= 0 ? "+" : ""}${current - previous}`
        : "Sem histórico"
    const rateLabel = dashboard.resolution.rate !== null
      ? `${dashboard.resolution.rate.toFixed(1)}% dos tickets foram resolvidos`
      : "Taxa indisponível"
    return { positive, badgeLabel, rateLabel }
  }, [dashboard])

  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 em atendimento</CardDescription>
          <CardTitle className="text-3xl font-semibold tabular-nums">
            {inProgressSummary ? inProgressSummary.current : <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
              ? "Sem histórico recente"
              : trendInfo.value >= 0
                ? "Acima das últimas 24h"
                : "Abaixo das últimas 24h"}
          </div>
          <span>Base: tickets ativos (1ª resposta registrada) nas últimas 24h.</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 className="leading-snug">
            <span className="block">Tempo médio da</span>
            <span className="block">1ª resposta</span>
          </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 className="leading-snug">
            <span className="block">Tickets resolvidos</span>
            <span className="block">(7 dias)</span>
          </CardDescription>
          <CardTitle className="text-3xl font-semibold tabular-nums">
            {dashboard ? dashboard.resolution.resolvedLast7d : <Skeleton className="h-8 w-12" />}
          </CardTitle>
          <CardAction>
            <Badge
              variant="outline"
              className={cn(
                "rounded-full gap-1 px-2 py-1 text-xs",
                resolutionInfo.positive ? "text-emerald-600" : "text-amber-600"
              )}
            >
              {resolutionInfo.positive ? (
                <IconTrendingUp className="size-3.5" />
              ) : (
                <IconTrendingDown className="size-3.5" />
              )}
              {resolutionInfo.badgeLabel}
            </Badge>
          </CardAction>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1 text-sm text-muted-foreground">
          <span className="text-foreground">{resolutionInfo.rateLabel}</span>
          <span>Comparação com os 7 dias anteriores.</span>
        </CardFooter>
      </Card>
    </div>
  )
}
