"use client"

import { useMemo } from "react"
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 { useAuth } from "@/lib/auth-client"
import Link from "next/link"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty"
import { Spinner } from "@/components/ui/spinner"
import { Button } from "@/components/ui/button"
import { PortalTicketCard } from "@/components/portal/portal-ticket-card"

export function PortalTicketList() {
  const { convexUserId, session, machineContext } = useAuth()

  const viewerId = (convexUserId ?? machineContext?.assignedUserId ?? null) as Id<"users"> | null

  const ticketsRaw = useQuery(
    api.tickets.list,
    viewerId
      ? {
          tenantId: session?.user.tenantId ?? DEFAULT_TENANT_ID,
          viewerId,
          limit: 100,
        }
      : "skip"
  )

  const tickets = useMemo(() => {
    if (!ticketsRaw) return []
    return mapTicketsFromServerList((ticketsRaw as unknown[]) ?? [])
  }, [ticketsRaw])

  const isLoading = Boolean(viewerId && ticketsRaw === undefined)

  if (isLoading) {
    return (
      <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
        <CardContent className="flex h-56 flex-col items-center justify-center gap-3 px-5 text-center">
          <div className="inline-flex size-12 items-center justify-center rounded-full border border-slate-200 bg-slate-50">
            <Spinner className="size-5 text-neutral-600" />
          </div>
          <div className="space-y-1">
            <CardTitle className="text-lg font-semibold text-neutral-900">Carregando chamados...</CardTitle>
            <p className="text-sm text-neutral-600">
              Estamos buscando seus chamados mais recentes. Isso deve levar apenas alguns instantes.
            </p>
          </div>
        </CardContent>
      </Card>
    )
  }

  if (!viewerId || !tickets.length) {
    return (
      <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
        <CardHeader className="px-5 py-5">
          <CardTitle className="text-lg font-semibold text-neutral-900">Meus chamados</CardTitle>
        </CardHeader>
        <CardContent className="px-5 pb-6">
          <Empty>
            <EmptyHeader>
              <EmptyMedia variant="icon">
                <span className="inline-block size-3 rounded-full border border-slate-300 bg-[#00e8ff]" />
              </EmptyMedia>
              <EmptyTitle className="text-neutral-900">Nenhum ticket encontrado</EmptyTitle>
              <EmptyDescription className="text-neutral-600">
                Ajuste os filtros ou crie um novo ticket.
              </EmptyDescription>
            </EmptyHeader>
            <div className="mt-4">
              <Button asChild className="rounded-full bg-neutral-900 px-4 text-sm font-semibold text-white hover:bg-neutral-900/90">
                <Link href="/portal/tickets/new">Novo ticket</Link>
              </Button>
            </div>
          </Empty>
        </CardContent>
      </Card>
    )
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-neutral-900">Meus chamados</h2>
          <p className="text-sm text-neutral-600">Acompanhe seus tickets e veja as últimas atualizações.</p>
        </div>
      </div>
      <div className="grid gap-4">
        {(tickets as Ticket[]).map((ticket) => (
          <PortalTicketCard key={ticket.id} ticket={ticket} />
        ))}
      </div>
    </div>
  )
}
