"use client"

import { useMemo, useState } from "react"
import { useQuery } from "convex/react"
// @ts-expect-error Convex runtime API lacks TypeScript definitions
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, TicketQueueSummary } from "@/lib/schemas/ticket"
import { TicketsFilters, TicketFiltersState, defaultTicketFilters } from "@/components/tickets/tickets-filters"
import { TicketsTable } from "@/components/tickets/tickets-table"
import { useAuth } from "@/lib/auth-client"

export function TicketsView() {
  const [filters, setFilters] = useState<TicketFiltersState>(defaultTicketFilters)
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID

  const queues = useQuery(
    convexUserId ? api.queues.summary : "skip",
    convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
  ) as TicketQueueSummary[] | undefined
  const ticketsRaw = useQuery(
    api.tickets.list,
    convexUserId
      ? {
          tenantId,
          viewerId: convexUserId as Id<"users">,
          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,
        }
      : "skip"
  )

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

  const filteredTickets = useMemo(() => {
    if (!filters.queue) return tickets
    return tickets.filter((t: Ticket) => 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) => q.name)} />
      {ticketsRaw === undefined ? (
        <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
          <div className="grid gap-3">
            {Array.from({ length: 6 }).map((_, i) => (
              <div key={i} className="flex items-center justify-between gap-3">
                <div className="h-4 w-48 animate-pulse rounded bg-slate-100" />
                <div className="h-4 w-24 animate-pulse rounded bg-slate-100" />
              </div>
            ))}
          </div>
        </div>
      ) : (
        <TicketsTable tickets={filteredTickets} />
      )}
    </div>
  )
}

