"use client"

import { useMemo } from "react"
import Link from "next/link"
import { useQuery } from "convex/react"
import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import { Inbox } from "lucide-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 { mapTicketsFromServerList } from "@/lib/mappers/ticket"
import type { Ticket } from "@/lib/schemas/ticket"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { TicketStatusBadge } from "@/components/tickets/status-badge"
import { TicketPriorityPill } from "@/components/tickets/priority-pill"

const MAX_TICKETS = 3

export function MyTicketsPanel() {
  const { convexUserId, isStaff, session } = useAuth()
  const tenantId = session?.user?.tenantId ?? DEFAULT_TENANT_ID
  const enabled = Boolean(convexUserId && isStaff)
  const ticketsResult = useQuery(
    api.tickets.list,
    enabled
      ? {
          tenantId,
          viewerId: convexUserId as Id<"users">,
          assigneeId: convexUserId as Id<"users">,
          limit: 60,
        }
      : "skip"
  )
  const tickets = useMemo(() => {
    if (!Array.isArray(ticketsResult)) return []
    const parsed = mapTicketsFromServerList(ticketsResult as unknown[]).filter(
      (ticket) => ticket.status !== "RESOLVED"
    )
    return parsed
  }, [ticketsResult])

  const visibleTickets = tickets.slice(0, MAX_TICKETS)

  return (
    <Card className="rounded-3xl border border-border/60 shadow-sm">
      <CardHeader>
        <div className="flex items-center justify-between gap-3">
          <div>
            <CardTitle className="text-base font-semibold">Minhas tarefas</CardTitle>
            <CardDescription>Chamados atribuídos a você e ainda em progresso</CardDescription>
          </div>
          {convexUserId ? (
            <Link
              href={`/tickets?assignee=${String(convexUserId)}`}
              className="text-sm font-semibold text-[#006879] underline-offset-4 transition-colors hover:text-[#004d5a] hover:underline"
            >
              Ver todos
            </Link>
          ) : null}
        </div>
      </CardHeader>
      <CardContent className="space-y-3">
        {!enabled ? (
          <div className="flex flex-col items-center gap-3 rounded-2xl border border-dashed border-border/60 bg-muted/40 px-4 py-6 text-center text-sm text-muted-foreground">
            <Inbox className="size-6" />
            <p>Disponível apenas para usuários internos.</p>
          </div>
        ) : ticketsResult === undefined ? (
          <div className="space-y-2">
            {Array.from({ length: MAX_TICKETS }).map((_, index) => (
              <Skeleton key={`mytickets-skeleton-${index}`} className="h-20 w-full rounded-2xl" />
            ))}
          </div>
        ) : visibleTickets.length === 0 ? (
          <div className="rounded-2xl border border-dashed border-border/60 bg-muted/40 px-4 py-6 text-center text-sm text-muted-foreground">
            Nenhum ticket atribuído para hoje. Aproveite para ajudar na triagem ou revisar filas em risco.
          </div>
        ) : (
          <div className="space-y-3">
            {visibleTickets.map((ticket) => (
              <TicketRow key={ticket.id} ticket={ticket} />
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )
}

function TicketRow({ ticket }: { ticket: Ticket }) {
  const queueLabel = ticket.queue ?? "Sem fila"
  const updatedLabel = formatDistanceToNow(ticket.updatedAt, { addSuffix: true, locale: ptBR })
  const categoryBadges = [ticket.category?.name, ticket.subcategory?.name].filter(
    (value): value is string => Boolean(value)
  )
  const badgeClass =
    "rounded-lg border border-slate-300 px-3.5 py-1.5 text-sm font-medium text-slate-600 transition-colors"

  return (
    <Link
      href={`/tickets/${ticket.id}`}
      className="group relative flex flex-col gap-3 rounded-2xl border border-border/70 bg-white/90 px-5 py-4 text-left shadow-sm transition hover:-translate-y-0.5 hover:border-border hover:shadow-md"
    >
      <div className="absolute right-5 top-4 flex flex-col items-end gap-2 sm:flex-row sm:items-center">
        <TicketStatusBadge status={ticket.status} className="h-8 px-3.5 text-sm" />
        <TicketPriorityPill priority={ticket.priority} className="h-8 px-3.5 text-sm" />
      </div>
      <div className="flex flex-col gap-2 pr-0">
        <div className="flex flex-col">
          <span className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
            #{ticket.reference} • {queueLabel}
          </span>
          <span className="line-clamp-1 pr-32 text-base font-semibold text-neutral-900">{ticket.subject}</span>
        </div>
      </div>
      <div className="flex flex-wrap items-center gap-2 text-sm text-neutral-600">
        {categoryBadges.length > 0 ? (
          categoryBadges.map((label) => (
            <span key={label} className={badgeClass}>
              {label}
            </span>
          ))
        ) : (
          <span className={badgeClass}>Sem categoria</span>
        )}
        <span className={badgeClass}>Atualizado {updatedLabel}</span>
      </div>
    </Link>
  )
}
