"use client"

import Link from "next/link"
import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import { useQuery } from "convex/react"
// @ts-expect-error Convex runtime API lacks TS declarations
import { api } from "@/convex/_generated/api"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { mapTicketsFromServerList } from "@/lib/mappers/ticket"
import type { Ticket } from "@/lib/schemas/ticket"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { TicketPriorityPill } from "@/components/tickets/priority-pill"
import { TicketStatusBadge } from "@/components/tickets/status-badge"

const metaBadgeClass =
  "inline-flex items-center gap-1 rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-[11px] font-semibold text-neutral-700"

const channelLabel: Record<string, string> = {
  EMAIL: "E-mail",
  WHATSAPP: "WhatsApp",
  CHAT: "Chat",
  PHONE: "Telefone",
  API: "API",
  MANUAL: "Manual",
}

function TicketRow({ ticket }: { ticket: Ticket }) {
  return (
    <div className="rounded-xl border border-slate-200 bg-white/60 p-4 transition hover:border-slate-300 hover:bg-white">
      <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
        <div className="min-w-0 space-y-2">
          <div className="flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
            <span className="text-neutral-900">#{ticket.reference}</span>
            <span className="rounded-full bg-[#00e8ff]/15 px-2 py-0.5 text-[11px] font-semibold text-[#006879]">
              {ticket.queue ?? "Sem fila"}
            </span>
          </div>
          <div className="space-y-1">
            <Link href={`/tickets/${ticket.id}`} className="line-clamp-1 text-base font-semibold text-neutral-900 transition hover:text-neutral-700">
              {ticket.subject}
            </Link>
            <p className="line-clamp-2 text-sm text-neutral-600">{ticket.summary ?? "Sem resumo"}</p>
          </div>
          <div className="flex flex-wrap items-center gap-2 text-xs text-neutral-600">
            <span className="font-semibold text-neutral-700">{ticket.requester.name}</span>
            <span className="text-neutral-400">•</span>
            <span>{formatDistanceToNow(ticket.updatedAt, { addSuffix: true, locale: ptBR })}</span>
          </div>
        </div>
        <div className="flex shrink-0 flex-col items-stretch gap-2 text-right">
          <TicketStatusBadge status={ticket.status} />
          <TicketPriorityPill priority={ticket.priority} />
          <div className="flex flex-wrap justify-end gap-2 text-xs">
            <Badge className={metaBadgeClass}>{channelLabel[ticket.channel] ?? ticket.channel}</Badge>
            <Badge className={metaBadgeClass}>{ticket.assignee?.name ?? "Sem responsável"}</Badge>
            {ticket.category ? (
              <Badge className="inline-flex items-center gap-1 rounded-full border border-[#00e8ff]/50 bg-[#00e8ff]/10 px-3 py-1 text-[11px] font-semibold text-[#02414d]">
                {ticket.category.name}
                {ticket.subcategory ? ` • ${ticket.subcategory.name}` : ""}
              </Badge>
            ) : (
              <Badge className={metaBadgeClass}>Sem categoria</Badge>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

export function RecentTicketsPanel() {
  const ticketsRaw = useQuery(api.tickets.list, { tenantId: DEFAULT_TENANT_ID, limit: 6 })

  if (ticketsRaw === undefined) {
    return (
      <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
        <CardHeader className="pb-2">
          <CardTitle className="text-base font-semibold text-neutral-900">Últimos chamados</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          {Array.from({ length: 4 }).map((_, index) => (
            <div key={index} className="rounded-xl border border-slate-100 bg-slate-50/60 p-4">
              <Skeleton className="mb-2 h-4 w-48" />
              <Skeleton className="h-3 w-64" />
            </div>
          ))}
        </CardContent>
      </Card>
    )
  }

  const tickets = mapTicketsFromServerList((ticketsRaw ?? []) as unknown[]).slice(0, 6)

  return (
    <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
      <CardHeader className="flex flex-row items-center justify-between pb-4">
        <CardTitle className="text-base font-semibold text-neutral-900">Últimos chamados</CardTitle>
        <Button asChild size="sm" variant="ghost" className="text-sm font-semibold text-[#006879] hover:bg-[#00e8ff]/10">
          <Link href="/tickets">Ver todos</Link>
        </Button>
      </CardHeader>
      <CardContent className="space-y-3">
        {tickets.length === 0 ? (
          <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50/80 p-6 text-center text-sm text-neutral-600">
            Nenhum ticket recente encontrado.
          </div>
        ) : (
          tickets.map((ticket) => <TicketRow key={ticket.id} ticket={ticket} />)
        )}
      </CardContent>
    </Card>
  )
}
