"use client"

import { useEffect, useRef, useState } from "react"
import { useRouter } from "next/navigation"
import { format, formatDistanceToNowStrict } from "date-fns"
import { ptBR } from "date-fns/locale"
import { type LucideIcon, Code, FileText, Mail, MessageCircle, MessageSquare, Phone } from "lucide-react"

import type { Ticket, TicketChannel, TicketStatus } from "@/lib/schemas/ticket"
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"

const channelLabel: Record<TicketChannel, string> = {
  EMAIL: "E-mail",
  WHATSAPP: "WhatsApp",
  CHAT: "Chat",
  PHONE: "Telefone",
  API: "API",
  MANUAL: "Manual",
}

const channelIcon: Record<TicketChannel, LucideIcon> = {
  EMAIL: Mail,
  WHATSAPP: MessageCircle,
  CHAT: MessageSquare,
  PHONE: Phone,
  API: Code,
  MANUAL: FileText,
}

const cellClass = "px-4 py-4 align-middle text-sm text-neutral-700 whitespace-normal first:pl-5 last:pr-6"
const channelIconBadgeClass = "inline-flex size-8 items-center justify-center rounded-full border border-slate-200 bg-slate-50 text-neutral-700"
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"

const statusLabel: Record<TicketStatus, string> = {
  PENDING: "Pendente",
  AWAITING_ATTENDANCE: "Aguardando atendimento",
  PAUSED: "Pausado",
  RESOLVED: "Resolvido",
}

const statusTone: Record<TicketStatus, string> = {
  PENDING: "text-slate-700",
  AWAITING_ATTENDANCE: "text-sky-700",
  PAUSED: "text-violet-700",
  RESOLVED: "text-emerald-700",
}

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 AssigneeCell({ ticket }: { ticket: Ticket }) {
  if (!ticket.assignee) {
    return <span className="text-sm text-neutral-600">Sem responsável</span>
  }

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

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

export type TicketsTableProps = {
  tickets?: Ticket[]
}

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

  useEffect(() => {
    const interval = setInterval(() => {
      setNow(Date.now())
    }, 1000)
    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">
          <Table className="w-full min-w-[920px] overflow-hidden rounded-3xl">
            <TableHeader className="bg-slate-100/80">
              <TableRow className="bg-transparent text-[11px] uppercase tracking-wide text-neutral-600">
                <TableHead className="w-[110px] px-4 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 sm:w-[120px]">
                Ticket
              </TableHead>
                <TableHead className="w-[38%] px-4 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 sm:w-[40%]">
                Assunto
              </TableHead>
                <TableHead className="hidden w-[120px] pl-6 pr-3 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 lg:table-cell">
                Fila
              </TableHead>
                <TableHead className="hidden w-[70px] pl-6 pr-3 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 md:table-cell sm:w-[80px]">
                Canal
              </TableHead>
                <TableHead className="hidden w-[150px] pl-6 pr-3 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 lg:table-cell xl:w-[180px]">
                Empresa
              </TableHead>
                <TableHead className="hidden w-[90px] px-4 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 md:table-cell lg:w-[100px]">
                Prioridade
              </TableHead>
                <TableHead className="w-[160px] pl-6 pr-3 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 sm:w-[200px] lg:pl-10 xl:w-[230px] xl:pl-14">
                Status
              </TableHead>
                <TableHead className="hidden w-[110px] px-4 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 lg:table-cell">
                Tempo
              </TableHead>
                <TableHead className="hidden w-[180px] px-4 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 xl:table-cell xl:w-[200px]">
                Responsável
              </TableHead>
                <TableHead className="w-[130px] px-4 py-3 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-6 last:pr-6 sm:w-[140px]">
                Atualizado
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {safeTickets.map((ticket) => {
              const ChannelIcon = channelIcon[ticket.channel] ?? MessageCircle

              return (
              <TableRow
                key={ticket.id}
                className={`${tableRowClass} cursor-pointer`}
                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}>
                  <div className="flex flex-col gap-1">
                    <span className="font-semibold tracking-tight text-neutral-900">
                      #{ticket.reference}
                    </span>
                    <span className="text-xs text-neutral-500">
                      {ticket.queue ?? "Sem fila"}
                    </span>
                  </div>
                </TableCell>
                <TableCell className={cellClass}>
                  <div className="flex flex-col gap-1.5 min-w-0">
                    <span className="text-[15px] font-semibold text-neutral-900 line-clamp-2 md:line-clamp-1 break-words">
                      {ticket.subject}
                    </span>
                    <span className="text-sm text-neutral-600 line-clamp-1 break-words max-w-[52ch]">
                      {ticket.summary ?? "Sem resumo"}
                    </span>
                    <div className="flex flex-col gap-1 text-xs text-neutral-500">
                      <span className="font-semibold text-neutral-700">{ticket.requester.name}</span>
                      {ticket.category ? (
                        <Badge className={categoryChipClass}>
                          {ticket.category.name}
                          {ticket.subcategory ? <span className="text-neutral-600"> • {ticket.subcategory.name}</span> : null}
                        </Badge>
                      ) : (
                        <span className="text-neutral-400">Sem categoria</span>
                      )}
                    </div>
                  </div>
                </TableCell>
                <TableCell className={`${cellClass} hidden lg:table-cell pl-6`}>
                  <span className="text-sm font-semibold text-neutral-800">
                    {ticket.queue ?? "Sem fila"}
                  </span>
                </TableCell>
                <TableCell className={`${cellClass} hidden md:table-cell pl-6`}>
                  <div className="flex items-center">
                    <span className="sr-only">Canal {channelLabel[ticket.channel]}</span>
                    <span
                      className={channelIconBadgeClass}
                      aria-hidden="true"
                      title={channelLabel[ticket.channel]}
                    >
                      <ChannelIcon className="size-4" />
                    </span>
                  </div>
                </TableCell>
                <TableCell className={`${cellClass} hidden lg:table-cell pl-6`}>
                  <span className="max-w-[160px] truncate text-sm text-neutral-800" title={((ticket.company ?? null) as { name?: string } | null)?.name ?? "—"}>
                    {((ticket.company ?? null) as { name?: string } | null)?.name ?? "—"}
                  </span>
                </TableCell>
                <TableCell className={`${cellClass} hidden md:table-cell px-4`}>
                  <div
                    className="flex justify-center"
                    onClick={(event) => event.stopPropagation()}
                    onKeyDown={(event) => event.stopPropagation()}
                  >
                    <PrioritySelect ticketId={ticket.id} value={ticket.priority} />
                  </div>
                </TableCell>
                <TableCell className={`${cellClass} pl-6 sm:pl-10 xl:pl-14`}>
                  <div className="flex flex-col gap-1">
                    <span className={cn("text-sm font-semibold break-words leading-tight max-w-[140px] sm:max-w-[180px] lg:max-w-[210px]", statusTone[ticket.status])}>
                      {statusLabel[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={`${cellClass} hidden lg:table-cell`}>
                  <div className="flex flex-col gap-1 text-sm text-neutral-600">
                    <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={`${cellClass} hidden xl:table-cell`}>
                  <AssigneeCell ticket={ticket} />
                </TableCell>
                <TableCell className={cellClass}>
                  <div className="flex flex-col leading-tight">
                    <span className="text-sm text-neutral-700">
                      {`há cerca de ${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>
  )
}
