"use client"

import { useMemo, useState } from "react"
import { useQuery } from "convex/react"
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { api } from "../../../convex/_generated/api"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { mapTicketsFromServerList } from "@/lib/mappers/ticket"
import { TicketsFilters, TicketFiltersState, defaultTicketFilters } from "@/components/tickets/tickets-filters"
import { TicketsTable } from "@/components/tickets/tickets-table"
import { Spinner } from "@/components/ui/spinner"

export function TicketsView() {
  const [filters, setFilters] = useState<TicketFiltersState>(defaultTicketFilters)

  const queues = useQuery(api.queues.summary, { tenantId: DEFAULT_TENANT_ID })
  const ticketsRaw = useQuery(api.tickets.list, {
    tenantId: DEFAULT_TENANT_ID,
    status: filters.status ?? undefined,
    priority: filters.priority ?? undefined,
    channel: filters.channel ?? undefined,
    queueId: undefined, // simplified: filter by queue name on client
    search: filters.search || undefined,
  })

  const tickets = useMemo(() => mapTicketsFromServerList((ticketsRaw ?? []) as any[]), [ticketsRaw])

  const filteredTickets = useMemo(() => {
    if (!filters.queue) return tickets
    return tickets.filter((t: any) => t.queue === filters.queue)
  }, [tickets, filters.queue])

  return (
    <div className="flex flex-col gap-6 px-4 lg:px-6">
      <TicketsFilters onChange={setFilters} queues={(queues ?? []).map((q: any) => q.name)} />
      {ticketsRaw === undefined ? (
        <div className="flex items-center gap-2 text-sm text-muted-foreground"><Spinner /> Carregando tickets…</div>
      ) : (
        <TicketsTable tickets={filteredTickets as any} />
      )}
    </div>
  )
}

