"use client"

import { memo, useEffect, useRef, useState } from "react"
import { useRouter } from "next/navigation"
import { format, formatDistanceToNowStrict } from "date-fns"
import { ptBR } from "date-fns/locale"
import { IconBuildingOff, IconCategory, IconHierarchyOff, IconUserOff } from "@tabler/icons-react"

import type { Ticket } from "@/lib/schemas/ticket"
import { useAuth } from "@/lib/auth-client"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty"
import { NewTicketDialog } from "@/components/tickets/new-ticket-dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { PrioritySelect } from "@/components/tickets/priority-select"
import { cn } from "@/lib/utils"
import { deriveServerOffset, toServerTimestamp } from "@/components/tickets/ticket-timer.utils"
import { getTicketStatusLabel, getTicketStatusTextClass } from "@/lib/ticket-status-style"
import { EmptyIndicator } from "@/components/ui/empty-indicator"

const cellClass =
  "px-3 py-4 sm:px-4 xl:px-3 xl:py-3 align-middle text-sm text-neutral-700 whitespace-normal " +
  "first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4"
const borderedCellClass = cellClass
const categoryChipClass = "inline-flex items-center gap-1 rounded-full bg-slate-200/60 px-2.5 py-1 text-[11px] font-medium text-neutral-700"
const tableRowClass =
  "group border-b border-slate-100 text-sm transition-colors hover:bg-slate-100/70 last:border-none"

function formatDuration(ms?: number) {
  if (!ms || ms <= 0) return "—"
  const totalSeconds = Math.floor(ms / 1000)
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60
  if (hours > 0) {
    return `${hours}h ${minutes.toString().padStart(2, "0")}m`
  }
  if (minutes > 0) {
    return `${minutes}m ${seconds.toString().padStart(2, "0")}s`
  }
  return `${seconds}s`
}

function formatQueueLabel(queue?: string | null) {
  if (!queue) {
    return { label: "Sem fila", title: "Sem fila" }
  }
  const normalized = queue.toLowerCase()
  if (normalized.startsWith("laboratorio")) {
    return { label: "Lab", title: queue }
  }
  return { label: queue, title: queue }
}

const AssigneeCell = memo(function AssigneeCell({ ticket, sessionUserId, sessionAvatarUrl }: { ticket: Ticket; sessionUserId?: string; sessionAvatarUrl?: string | null }) {
  if (!ticket.assignee) {
    return (
      <div className="flex items-center justify-center">
        <EmptyIndicator
          icon={IconUserOff}
          label="Sem responsável"
          className="h-10 w-10 border-neutral-200 bg-transparent text-neutral-400"
        />
      </div>
    )
  }

  const initials = ticket.assignee.name
    .split(" ")
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase())
    .join("")

  // Usa o avatar da sessao se o assignee for o usuario logado (garante sincronizacao)
  const isCurrentUser = sessionUserId && ticket.assignee.id === sessionUserId
  const avatarUrl = isCurrentUser ? sessionAvatarUrl : ticket.assignee.avatarUrl

  return (
    <div className="flex min-w-0 flex-col items-center gap-2 text-center">
      <Avatar className="size-8 border border-slate-200">
        <AvatarImage src={avatarUrl ?? undefined} alt={ticket.assignee.name} />
        <AvatarFallback>{initials}</AvatarFallback>
      </Avatar>
      <div className="flex min-w-0 flex-col items-center">
        <span className="truncate text-sm font-semibold leading-none text-neutral-900 max-w-[14ch]">
          {ticket.assignee.name}
        </span>
        <span className="truncate text-xs text-neutral-600 max-w-[16ch]">
          {ticket.assignee.teams?.[0] ?? "Agente"}
        </span>
      </div>
    </div>
  )
})

export type TicketsTableProps = {
  tickets?: Ticket[]
  enteringIds?: Set<string>
}

export function TicketsTable({ tickets, enteringIds }: TicketsTableProps) {
  const safeTickets = tickets ?? []
  const [now, setNow] = useState(() => Date.now())
  const serverOffsetRef = useRef<number>(0)
  const router = useRouter()
  const { session } = useAuth()

  // Atualiza o timer a cada 15 segundos (otimizado de 1s)
  useEffect(() => {
    const interval = setInterval(() => {
      setNow(Date.now())
    }, 15000)
    return () => clearInterval(interval)
  }, [])

  useEffect(() => {
    const candidates = (tickets ?? [])
      .map((ticket) => (typeof ticket.workSummary?.serverNow === "number" ? ticket.workSummary.serverNow : null))
      .filter((value): value is number => value !== null)
    if (candidates.length === 0) return
    const latestServerNow = candidates[candidates.length - 1]
    serverOffsetRef.current = deriveServerOffset({
      currentOffset: serverOffsetRef.current,
      localNow: Date.now(),
      serverNow: latestServerNow,
    })
  }, [tickets])

  const getWorkedMs = (ticket: Ticket) => {
    const base = ticket.workSummary?.totalWorkedMs ?? 0
    const activeStart = ticket.workSummary?.activeSession?.startedAt
    if (activeStart instanceof Date) {
      const alignedNow = toServerTimestamp(now, serverOffsetRef.current)
      return base + Math.max(0, alignedNow - activeStart.getTime())
    }
    return base
  }

  return (
    <Card className="gap-0 rounded-3xl border border-slate-200 bg-white py-0 shadow-sm">
      <CardContent className="p-0">
        <div className="w-full overflow-x-auto xl:overflow-x-hidden">
          <Table className="w-full overflow-hidden rounded-3xl xl:table-fixed">
            <TableHeader className="bg-slate-100/80">
              <TableRow className="bg-transparent text-[11px] uppercase tracking-wide text-neutral-600">
                <TableHead className="px-3 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4 xl:w-[7%] xl:border-l xl:border-slate-200 first:xl:border-l-0">
                  Ticket
                </TableHead>
                <TableHead className="px-3 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4 xl:w-[22%] xl:border-l xl:border-slate-200 first:xl:border-l-0">
                  Assunto
                </TableHead>
                <TableHead className="hidden lg:table-cell pl-3 pr-3 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4 xl:w-[11%] xl:border-l xl:border-slate-200 first:xl:border-l-0">
                  Empresa
                </TableHead>
                <TableHead className="hidden md:table-cell px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4 xl:w-[10%] xl:border-l xl:border-slate-200 first:xl:border-l-0">
                  Prioridade
                </TableHead>
                <TableHead className="hidden lg:table-cell pl-3 pr-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4 xl:w-[9%] xl:border-l xl:border-slate-200 first:xl:border-l-0">
                  Fila
                </TableHead>
                <TableHead className="pl-3 pr-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4 xl:w-[10%] xl:border-l xl:border-slate-200 first:xl:border-l-0">
                  Status
                </TableHead>
                <TableHead className="hidden lg:table-cell px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4 xl:w-[6%] xl:border-l xl:border-slate-200 first:xl:border-l-0">
                  Tempo
                </TableHead>
                <TableHead className="hidden xl:table-cell px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4 xl:w-[15%] xl:border-l xl:border-slate-200 first:xl:border-l-0">
                  Responsável
                </TableHead>
                <TableHead className="px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-3 last:pr-3 sm:first:pl-4 sm:last:pr-4 xl:first:pl-4 xl:last:pr-4 xl:w-[10%] xl:border-l xl:border-slate-200 first:xl:border-l-0">
                  Atualizado
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {safeTickets.map((ticket) => {
                const rowClass = cn(
                  `${tableRowClass} cursor-pointer`,
                  enteringIds?.has(ticket.id) ? "recent-ticket-enter" : undefined,
                )

                const queueDisplay = formatQueueLabel(ticket.queue)

                return (
                  <TableRow
                    key={ticket.id}
                    className={rowClass}
                    role="link"
                    tabIndex={0}
                    onClick={() => router.push(`/tickets/${ticket.id}`)}
                    onKeyDown={(event) => {
                      if (event.key === "Enter" || event.key === " ") {
                        event.preventDefault()
                        router.push(`/tickets/${ticket.id}`)
                      }
                    }}
                  >
                  <TableCell className={`${cellClass} overflow-hidden`}>
                    <div className="flex min-w-0 flex-col items-start gap-1">
                      <span className="font-semibold tracking-tight text-neutral-900">#{ticket.reference}</span>
                      <div className="flex items-center gap-1 text-xs text-neutral-500">
                        {ticket.queue ? (
                          <span className="truncate">{ticket.queue}</span>
                        ) : (
                          <EmptyIndicator
                            icon={IconHierarchyOff}
                            label="Sem fila"
                            className="h-6 w-6 border-neutral-200 bg-transparent text-neutral-400"
                          />
                        )}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className={cellClass}>
                    <div className="flex min-w-0 flex-col gap-1.5">
                      <span className="text-[15px] font-semibold text-neutral-900 line-clamp-2 md:line-clamp-1 break-words">
                        {ticket.subject}
                      </span>
                      {ticket.formTemplateLabel || ticket.formTemplate ? (
                        <div className="flex items-center gap-2">
                          <Badge className="rounded-full border border-sky-200 bg-sky-50 px-2.5 py-0.5 text-[11px] font-semibold text-sky-700">
                            {ticket.formTemplateLabel ?? ticket.formTemplate}
                          </Badge>
                        </div>
                      ) : null}
                      <div className="flex flex-col gap-1 text-xs text-neutral-500">
                        {ticket.category ? (
                          <Badge className={categoryChipClass}>
                            {ticket.category.name}
                            {ticket.subcategory ? (
                              <span
                                className="hidden min-[2000px]:inline text-neutral-600"
                                title={ticket.subcategory.name}
                              >
                                {" "}
                                • {ticket.subcategory.name}
                              </span>
                            ) : null}
                          </Badge>
                        ) : (
                          <EmptyIndicator
                            icon={IconCategory}
                            label="Sem categoria"
                            className="h-6 w-6 border-neutral-200 bg-transparent text-neutral-400"
                          />
                        )}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className={`${cellClass} hidden lg:table-cell overflow-hidden`}>
                    <div className="flex min-w-0 flex-col gap-1">
                      <span className="truncate font-semibold text-neutral-800" title={ticket.requester.name}>
                        {ticket.requester.name}
                      </span>
                      {ticket.company?.name ? (
                        <span className="truncate text-sm text-neutral-600" title={ticket.company.name}>
                          {ticket.company.name}
                        </span>
                      ) : (
                        <EmptyIndicator
                          icon={IconBuildingOff}
                          label="Nenhuma empresa vinculada"
                          className="h-7 w-7 border-neutral-200 bg-transparent text-neutral-400"
                        />
                      )}
                    </div>
                  </TableCell>
                  <TableCell className={`${borderedCellClass} hidden md:table-cell text-center`}>
                    <div
                      className="relative z-[1] flex justify-center"
                      onClick={(event) => event.stopPropagation()}
                      onKeyDown={(event) => event.stopPropagation()}
                    >
                      <PrioritySelect
                        className="min-w-[6.5rem] max-w-[8rem]"
                        ticketId={ticket.id}
                        value={ticket.priority}
                      />
                    </div>
                  </TableCell>
                  <TableCell className={`${borderedCellClass} hidden lg:table-cell overflow-hidden text-center`}>
                    {ticket.queue ? (
                      <span
                        className="mx-auto truncate text-sm font-semibold text-neutral-800"
                        title={queueDisplay.title}
                      >
                        {queueDisplay.label}
                      </span>
                    ) : (
                      <div className="flex justify-center">
                        <EmptyIndicator
                          icon={IconHierarchyOff}
                          label="Sem fila"
                          className="h-7 w-7 border-neutral-200 bg-transparent text-neutral-400"
                        />
                      </div>
                    )}
                  </TableCell>
                  <TableCell className={`${borderedCellClass} overflow-hidden`}>
                    <div className="flex min-w-0 flex-col items-center gap-1 text-center">
                      <span
                        className={cn(
                          "text-sm font-semibold leading-tight truncate text-center",
                          "max-w-[14ch] sm:max-w-[18ch] xl:max-w-[20ch]",
                          getTicketStatusTextClass(ticket.status)
                        )}
                      >
                        {getTicketStatusLabel(ticket.status)}
                      </span>
                      {ticket.metrics?.timeWaitingMinutes ? (
                        <span className="text-xs text-neutral-500">
                          Em espera há {ticket.metrics.timeWaitingMinutes} min
                        </span>
                      ) : null}
                    </div>
                  </TableCell>
                  <TableCell className={`${borderedCellClass} hidden lg:table-cell`}>
                    <div className="flex flex-col items-center gap-1 text-sm text-neutral-600 text-center">
                      <span className="font-semibold text-neutral-800">{formatDuration(getWorkedMs(ticket))}</span>
                      {ticket.workSummary?.activeSession ? (
                        <span className="text-xs text-neutral-500">Em andamento</span>
                      ) : null}
                    </div>
                  </TableCell>
                  <TableCell className={`${borderedCellClass} hidden xl:table-cell overflow-hidden`}>
                    <AssigneeCell ticket={ticket} sessionUserId={session?.user?.id} sessionAvatarUrl={session?.user?.avatarUrl} />
                  </TableCell>
                  <TableCell className={borderedCellClass}>
                    <div className="flex flex-col items-center leading-tight text-center">
                      <span className="text-sm text-neutral-700 whitespace-normal">
                        {`há ${formatDistanceToNowStrict(ticket.updatedAt, { locale: ptBR })}`}
                      </span>
                      <span className="text-xs text-neutral-500">
                        {format(ticket.updatedAt, "dd/MM/yyyy HH:mm")}
                      </span>
                    </div>
                  </TableCell>
                </TableRow>
              )
            })}
            </TableBody>
          </Table>
        </div>
        {safeTickets.length === 0 && (
          <Empty className="my-6">
            <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>
            <EmptyContent>
              <NewTicketDialog />
            </EmptyContent>
          </Empty>
        )}
      </CardContent>
    </Card>
  )
}
