"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"

import { tickets as ticketsMock } from "@/lib/mocks/tickets"
import type { Ticket } 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 { TicketPriorityPill } from "@/components/tickets/priority-pill"
import { TicketStatusBadge } from "@/components/tickets/status-badge"

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

const cellClass = "px-6 py-5 align-top text-sm text-neutral-700 first:pl-8 last:pr-8"
const queueBadgeClass = "inline-flex items-center rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs font-semibold text-neutral-700"
const channelBadgeClass = "inline-flex items-center gap-2 rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs font-semibold text-neutral-700"
const tagBadgeClass = "inline-flex items-center rounded-full border border-slate-200 bg-slate-50 px-2.5 py-0.5 text-[11px] font-medium text-neutral-600"
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 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 = ticketsMock }: TicketsTableProps) {
  const [now, setNow] = useState(() => Date.now())

  useEffect(() => {
    const interval = setInterval(() => {
      setNow(Date.now())
    }, 1000)
    return () => clearInterval(interval)
  }, [])

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

  return (
    <Card className="rounded-3xl border border-slate-200 bg-white shadow-sm">
      <CardContent className="p-0">
        <Table className="min-w-full 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-[120px] px-6 py-4 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-8 last:pr-8">
                Ticket
              </TableHead>
              <TableHead className="px-6 py-4 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-8 last:pr-8">
                Assunto
              </TableHead>
              <TableHead className="hidden px-6 py-4 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-8 last:pr-8 lg:table-cell">
                Fila
              </TableHead>
              <TableHead className="hidden px-6 py-4 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-8 last:pr-8 md:table-cell">
                Canal
              </TableHead>
              <TableHead className="hidden px-6 py-4 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-8 last:pr-8 md:table-cell">
                Prioridade
              </TableHead>
              <TableHead className="px-6 py-4 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-8 last:pr-8">
                Status
              </TableHead>
              <TableHead className="hidden px-6 py-4 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-8 last:pr-8 lg:table-cell">
                Tempo
              </TableHead>
              <TableHead className="hidden px-6 py-4 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-8 last:pr-8 xl:table-cell">
                Responsável
              </TableHead>
              <TableHead className="px-6 py-4 text-left text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-8 last:pr-8">
                Atualizado
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {tickets.map((ticket) => (
              <TableRow key={ticket.id} className={tableRowClass}>
                <TableCell className={cellClass}>
                  <div className="flex flex-col gap-1">
                    <Link
                      href={`/tickets/${ticket.id}`}
                      className="font-semibold tracking-tight text-neutral-900 transition hover:text-neutral-700"
                    >
                      #{ticket.reference}
                    </Link>
                    <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">
                    <Link
                      href={`/tickets/${ticket.id}`}
                      className="line-clamp-1 text-[15px] font-semibold text-neutral-900 transition hover:text-neutral-700"
                    >
                      {ticket.subject}
                    </Link>
                    <span className="line-clamp-1 text-sm text-neutral-600">
                      {ticket.summary ?? "Sem resumo"}
                    </span>
                    <div className="flex flex-wrap items-center gap-2 text-xs text-neutral-500">
                      <span className="font-semibold text-neutral-700">{ticket.requester.name}</span>
                      {ticket.tags?.map((tag) => (
                        <Badge key={tag} className={tagBadgeClass}>
                          {tag}
                        </Badge>
                      ))}
                    </div>
                  </div>
                </TableCell>
                <TableCell className={`${cellClass} hidden lg:table-cell`}>
                  <Badge className={queueBadgeClass}>{ticket.queue ?? "Sem fila"}</Badge>
                </TableCell>
                <TableCell className={`${cellClass} hidden md:table-cell`}>
                  <Badge className={channelBadgeClass}>
                    <span className="inline-block size-2 rounded-full bg-[#00d6eb]" />
                    {channelLabel[ticket.channel] ?? ticket.channel}
                  </Badge>
                </TableCell>
                <TableCell className={`${cellClass} hidden md:table-cell`}>
                  <TicketPriorityPill priority={ticket.priority} />
                </TableCell>
                <TableCell className={cellClass}>
                  <div className="flex flex-col gap-1">
                    <TicketStatusBadge status={ticket.status} />
                    {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}>
                  <span className="text-sm text-neutral-600">
                    {formatDistanceToNow(ticket.updatedAt, { addSuffix: true, locale: ptBR })}
                  </span>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
        {tickets.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>
  )
}
