"use client"

import { useEffect, useMemo, useRef, useState } from "react"
import Link from "next/link"
import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import { useQuery } from "convex/react"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
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"
import { useAuth } from "@/lib/auth-client"

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, entering }: { ticket: Ticket; entering: boolean }) {
  return (
    <div
      className={`rounded-xl border border-slate-200 bg-white/60 p-4 transition-all duration-300 hover:border-slate-300 hover:bg-white ${entering ? "recent-ticket-enter" : ""}`}
    >
      <div className="flex flex-col gap-4 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>
          {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="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">
              Sem categoria
            </Badge>
          )}
        </div>
        <div className="flex shrink-0 flex-col gap-3 text-right md:w-[220px]">
          <div className="flex flex-wrap justify-end gap-2">
            <TicketStatusBadge status={ticket.status} />
            <TicketPriorityPill priority={ticket.priority} />
          </div>
          <div className="flex flex-wrap justify-end gap-x-2 gap-y-1 text-xs text-neutral-600">
            <Badge className={metaBadgeClass}>{channelLabel[ticket.channel] ?? ticket.channel}</Badge>
            <Badge className={metaBadgeClass}>{ticket.assignee?.name ?? "Sem responsável"}</Badge>
          </div>
        </div>
      </div>
    </div>
  )
}

export function RecentTicketsPanel() {
  const { convexUserId } = useAuth()
  const ticketsRaw = useQuery(
    api.tickets.list,
    convexUserId ? { tenantId: DEFAULT_TENANT_ID, viewerId: convexUserId as Id<"users">, limit: 6 } : "skip"
  )
  const [enteringId, setEnteringId] = useState<string | null>(null)
  const previousIdsRef = useRef<string[]>([])

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

  useEffect(() => {
    if (ticketsRaw === undefined) {
      previousIdsRef.current = []
      return
    }
    const ids = tickets.map((ticket) => ticket.id)
    const previous = previousIdsRef.current
    if (!ids.length) {
      previousIdsRef.current = ids
      return
    }
    if (!previous.length) {
      previousIdsRef.current = ids
      return
    }
    const topId = ids[0]
    if (!previous.includes(topId)) {
      setEnteringId(topId)
    }
    previousIdsRef.current = ids
  }, [tickets, ticketsRaw])

  useEffect(() => {
    if (!enteringId) return
    const timer = window.setTimeout(() => setEnteringId(null), 600)
    return () => window.clearTimeout(timer)
  }, [enteringId])

  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>
    )
  }

  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} entering={ticket.id === enteringId} />
          ))
        )}
      </CardContent>
    </Card>
  )
}
