"use client"

import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { format, formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import { IconClock, IconDownload, IconInfoCircle, IconPlayerPause, IconPlayerPlay } from "@tabler/icons-react"
import { useMutation, useQuery } from "convex/react"
import { toast } from "sonner"
import { api } from "@/convex/_generated/api"

import { useAuth } from "@/lib/auth-client"
import type { Doc, Id } from "@/convex/_generated/dataModel"
import type { TicketWithDetails, TicketQueueSummary, TicketStatus } from "@/lib/schemas/ticket"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { PrioritySelect } from "@/components/tickets/priority-select"
import { DeleteTicketDialog } from "@/components/tickets/delete-ticket-dialog"
import { StatusSelect } from "@/components/tickets/status-select"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Textarea } from "@/components/ui/textarea"
import { Spinner } from "@/components/ui/spinner"
import { useTicketCategories } from "@/hooks/use-ticket-categories"
import { useDefaultQueues } from "@/hooks/use-default-queues"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"

interface TicketHeaderProps {
  ticket: TicketWithDetails
}

type WorkSummarySnapshot = {
  ticketId: Id<"tickets">
  totalWorkedMs: number
  internalWorkedMs: number
  externalWorkedMs: number
  activeSession: {
    id: Id<"ticketWorkSessions">
    agentId: Id<"users">
    startedAt: number
    workType?: string
  } | null
}

const cardClass = "relative space-y-4 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm"
const referenceBadgeClass = "inline-flex h-9 items-center gap-2 rounded-full border border-slate-200 bg-white px-3 text-sm font-semibold text-neutral-700"
const startButtonClass =
  "inline-flex items-center gap-1 rounded-lg border border-black bg-black px-3 py-1.5 text-sm font-semibold text-white transition hover:bg-[#18181b]/85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-black/30"
const pauseButtonClass =
  "inline-flex items-center gap-1 rounded-lg border border-black bg-black px-3 py-1.5 text-sm font-semibold text-white transition hover:bg-[#18181b]/85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#18181b]/30"
const editButtonClass =
  "inline-flex items-center gap-1 rounded-lg border border-black bg-black px-3 py-1.5 text-sm font-semibold text-white transition hover:bg-[#18181b]/85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#18181b]/30"
const selectTriggerClass = "h-8 w-full rounded-lg border border-slate-300 bg-white px-3 text-left text-sm font-medium text-neutral-800 shadow-sm focus:ring-0 data-[state=open]:border-[#00d6eb]"
const smallSelectTriggerClass = "h-8 w-full rounded-lg border border-slate-300 bg-white px-3 text-left text-sm font-medium text-neutral-800 shadow-sm focus:ring-0 data-[state=open]:border-[#00d6eb]"
const sectionLabelClass = "text-xs font-semibold uppercase tracking-wide text-neutral-500"
const sectionValueClass = "font-medium text-neutral-900"
const subtleBadgeClass =
  "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 EMPTY_CATEGORY_VALUE = "__none__"
const EMPTY_SUBCATEGORY_VALUE = "__none__"
const PAUSE_REASONS = [
  { value: "NO_CONTACT", label: "Falta de contato" },
  { value: "WAITING_THIRD_PARTY", label: "Aguardando terceiro" },
  { value: "IN_PROCEDURE", label: "Em procedimento" },
]

function formatDuration(durationMs: number) {
  if (durationMs <= 0) return "0s"
  const totalSeconds = Math.floor(durationMs / 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`
}

export function TicketSummaryHeader({ ticket }: TicketHeaderProps) {
  const { convexUserId, role, isStaff } = useAuth()
  const normalizedRole = (role ?? "").toLowerCase()
  const isManager = normalizedRole === "manager"
  const isAdmin = normalizedRole === "admin"
  useDefaultQueues(ticket.tenantId)
  const changeAssignee = useMutation(api.tickets.changeAssignee)
  const changeQueue = useMutation(api.tickets.changeQueue)
  const updateSubject = useMutation(api.tickets.updateSubject)
  const updateSummary = useMutation(api.tickets.updateSummary)
  const startWork = useMutation(api.tickets.startWork)
  const pauseWork = useMutation(api.tickets.pauseWork)
  const updateCategories = useMutation(api.tickets.updateCategories)
  const agents = (useQuery(api.users.listAgents, { tenantId: ticket.tenantId }) as Doc<"users">[] | undefined) ?? []
  const queuesEnabled = Boolean(isStaff && convexUserId)
  const queueArgs = queuesEnabled
    ? { tenantId: ticket.tenantId, viewerId: convexUserId as Id<"users"> }
    : "skip"
  const queues = (
    useQuery(queuesEnabled ? api.queues.summary : "skip", queueArgs) as TicketQueueSummary[] | undefined
  ) ?? []
  const { categories, isLoading: categoriesLoading } = useTicketCategories(ticket.tenantId)
  const [status] = useState<TicketStatus>(ticket.status)
  const workSummaryRemote = useQuery(
    api.tickets.workSummary,
    convexUserId
      ? { ticketId: ticket.id as Id<"tickets">, viewerId: convexUserId as Id<"users"> }
      : "skip"
  ) as
    | {
        ticketId: Id<"tickets">
        totalWorkedMs: number
        internalWorkedMs?: number
        externalWorkedMs?: number
        activeSession: {
          id: Id<"ticketWorkSessions">
          agentId: Id<"users">
          startedAt: number
          workType?: string
        } | null
      }
    | null
    | undefined

  const [editing, setEditing] = useState(false)
  const [subject, setSubject] = useState(ticket.subject)
  const [summary, setSummary] = useState(ticket.summary ?? "")
  const [categorySelection, setCategorySelection] = useState<{ categoryId: string; subcategoryId: string }>(
    {
      categoryId: ticket.category?.id ?? "",
      subcategoryId: ticket.subcategory?.id ?? "",
    }
  )
  const currentAssigneeId = ticket.assignee?.id ?? ""
  const [assigneeSelection, setAssigneeSelection] = useState(currentAssigneeId)
  const [saving, setSaving] = useState(false)
  const [pauseDialogOpen, setPauseDialogOpen] = useState(false)
  const [pauseReason, setPauseReason] = useState<string>(PAUSE_REASONS[0]?.value ?? "NO_CONTACT")
  const [pauseNote, setPauseNote] = useState("")
  const [pausing, setPausing] = useState(false)
  const [exportingPdf, setExportingPdf] = useState(false)
  const selectedCategoryId = categorySelection.categoryId
  const selectedSubcategoryId = categorySelection.subcategoryId
  const dirty = useMemo(
    () => subject !== ticket.subject || (summary ?? "") !== (ticket.summary ?? ""),
    [subject, summary, ticket.subject, ticket.summary]
  )
  const currentCategoryId = ticket.category?.id ?? ""
  const currentSubcategoryId = ticket.subcategory?.id ?? ""
  const categoryDirty = useMemo(() => {
    return selectedCategoryId !== currentCategoryId || selectedSubcategoryId !== currentSubcategoryId
  }, [selectedCategoryId, selectedSubcategoryId, currentCategoryId, currentSubcategoryId])
  const currentQueueName = ticket.queue ?? ""
  const isAvulso = Boolean(((ticket.company ?? null) as { isAvulso?: boolean } | null)?.isAvulso ?? false)
  const [queueSelection, setQueueSelection] = useState(currentQueueName)
  const queueDirty = useMemo(() => queueSelection !== currentQueueName, [queueSelection, currentQueueName])
  const assigneeDirty = useMemo(() => assigneeSelection !== currentAssigneeId, [assigneeSelection, currentAssigneeId])
  const formDirty = dirty || categoryDirty || queueDirty || assigneeDirty
  const companyLabel = useMemo(() => {
    if (ticket.company?.name) return ticket.company.name
    if (isAvulso) return "Cliente avulso"
    return "Sem empresa vinculada"
  }, [ticket.company?.name, isAvulso])

  const activeCategory = useMemo(
    () => categories.find((category) => category.id === selectedCategoryId) ?? null,
    [categories, selectedCategoryId]
  )
  const secondaryOptions = useMemo(() => activeCategory?.secondary ?? [], [activeCategory])
  const hasAssignee = Boolean(currentAssigneeId)
  const isCurrentResponsible = hasAssignee && convexUserId ? currentAssigneeId === convexUserId : false
  const canControlWork = isAdmin || !hasAssignee || isCurrentResponsible
  const canPauseWork = isAdmin || isCurrentResponsible
  const pauseDisabled = !canPauseWork
  const startDisabled = !canControlWork

  async function handleSave() {
    if (!convexUserId || !formDirty) {
      setEditing(false)
      return
    }

    setSaving(true)

    try {
      if (categoryDirty && !isManager) {
        toast.loading("Atualizando categoria...", { id: "ticket-category" })
        try {
          await updateCategories({
            ticketId: ticket.id as Id<"tickets">,
            categoryId: selectedCategoryId ? (selectedCategoryId as Id<"ticketCategories">) : null,
            subcategoryId: selectedSubcategoryId ? (selectedSubcategoryId as Id<"ticketSubcategories">) : null,
            actorId: convexUserId as Id<"users">,
          })
          toast.success("Categoria atualizada!", { id: "ticket-category" })
        } catch (categoryError) {
          toast.error("Não foi possível atualizar a categoria.", { id: "ticket-category" })
          setCategorySelection({
            categoryId: currentCategoryId,
            subcategoryId: currentSubcategoryId,
          })
          throw categoryError
        }
      } else if (categoryDirty && isManager) {
        setCategorySelection({
          categoryId: currentCategoryId,
          subcategoryId: currentSubcategoryId,
        })
      }

      if (queueDirty && !isManager) {
        const queue = queues.find((item) => item.name === queueSelection)
        if (!queue) {
          toast.error("Fila selecionada não está disponível.")
          setQueueSelection(currentQueueName)
          throw new Error("Fila inválida")
        }
        toast.loading("Atualizando fila...", { id: "queue" })
        try {
          await changeQueue({
            ticketId: ticket.id as Id<"tickets">,
            queueId: queue.id as Id<"queues">,
            actorId: convexUserId as Id<"users">,
          })
          toast.success("Fila atualizada!", { id: "queue" })
        } catch (queueError) {
          toast.error("Não foi possível atualizar a fila.", { id: "queue" })
          setQueueSelection(currentQueueName)
          throw queueError
        }
      } else if (queueDirty && isManager) {
        setQueueSelection(currentQueueName)
      }

      if (assigneeDirty && !isManager) {
        if (!assigneeSelection) {
          toast.error("Selecione um responsável válido.", { id: "assignee" })
          setAssigneeSelection(currentAssigneeId)
          throw new Error("invalid-assignee")
        } else {
          toast.loading("Atualizando responsável...", { id: "assignee" })
          try {
            await changeAssignee({
              ticketId: ticket.id as Id<"tickets">,
              assigneeId: assigneeSelection as Id<"users">,
              actorId: convexUserId as Id<"users">,
            })
            toast.success("Responsável atualizado!", { id: "assignee" })
          } catch (error) {
            console.error(error)
            toast.error("Não foi possível atualizar o responsável.", { id: "assignee" })
            setAssigneeSelection(currentAssigneeId)
            throw error
          }
        }
      } else if (assigneeDirty && isManager) {
        setAssigneeSelection(currentAssigneeId)
      }

      if (dirty) {
        toast.loading("Salvando alterações...", { id: "save-header" })
        if (subject !== ticket.subject) {
          await updateSubject({
            ticketId: ticket.id as Id<"tickets">,
            subject: subject.trim(),
            actorId: convexUserId as Id<"users">,
          })
        }
        if ((summary ?? "") !== (ticket.summary ?? "")) {
          await updateSummary({
            ticketId: ticket.id as Id<"tickets">,
            summary: (summary ?? "").trim(),
            actorId: convexUserId as Id<"users">,
          })
        }
        toast.success("Cabeçalho atualizado!", { id: "save-header" })
      }
      setEditing(false)
    } catch {
      toast.error("Não foi possível salvar.", { id: "save-header" })
    } finally {
      setSaving(false)
    }
  }

  function handleCancel() {
    setSubject(ticket.subject)
    setSummary(ticket.summary ?? "")
    setCategorySelection({
      categoryId: currentCategoryId,
      subcategoryId: currentSubcategoryId,
    })
    setQueueSelection(currentQueueName)
    setAssigneeSelection(currentAssigneeId)
    setEditing(false)
  }

  useEffect(() => {
    if (editing) return
    setCategorySelection({
      categoryId: ticket.category?.id ?? "",
      subcategoryId: ticket.subcategory?.id ?? "",
    })
    setQueueSelection(ticket.queue ?? "")
    setAssigneeSelection(ticket.assignee?.id ?? "")
  }, [editing, ticket.category?.id, ticket.subcategory?.id, ticket.queue, ticket.assignee?.id])

  useEffect(() => {
    if (!editing) return
    if (!selectedCategoryId) {
      if (selectedSubcategoryId) {
        setCategorySelection((prev) => ({ ...prev, subcategoryId: "" }))
      }
      return
    }

    const stillValid = secondaryOptions.some((option) => option.id === selectedSubcategoryId)
    if (!stillValid && selectedSubcategoryId) {
      setCategorySelection((prev) => ({ ...prev, subcategoryId: "" }))
    }
  }, [editing, secondaryOptions, selectedCategoryId, selectedSubcategoryId])

  const ticketActiveSession = ticket.workSummary?.activeSession ?? null
  const ticketActiveSessionStartedAtMs = ticketActiveSession ? ticketActiveSession.startedAt.getTime() : undefined
  const ticketActiveSessionWorkType = (ticketActiveSession as { workType?: string } | null)?.workType

  const initialWorkSummary = useMemo<WorkSummarySnapshot | null>(() => {
    if (!ticket.workSummary) return null
    return {
      ticketId: ticket.id as Id<"tickets">,
      totalWorkedMs: ticket.workSummary.totalWorkedMs ?? 0,
      internalWorkedMs: ticket.workSummary.internalWorkedMs ?? 0,
      externalWorkedMs: ticket.workSummary.externalWorkedMs ?? 0,
      activeSession: ticketActiveSession
        ? {
            id: ticketActiveSession.id as Id<"ticketWorkSessions">,
            agentId: ticketActiveSession.agentId as Id<"users">,
            startedAt: ticketActiveSessionStartedAtMs ?? ticketActiveSession.startedAt.getTime(),
            workType: (ticketActiveSessionWorkType ?? "INTERNAL").toString().toUpperCase(),
          }
        : null,
    }
  }, [
    ticket.id,
    ticket.workSummary,
    ticketActiveSession,
    ticketActiveSessionStartedAtMs,
    ticketActiveSessionWorkType,
  ])

  const [workSummary, setWorkSummary] = useState<WorkSummarySnapshot | null>(initialWorkSummary)

  useEffect(() => {
    setWorkSummary(initialWorkSummary)
  }, [initialWorkSummary])

  useEffect(() => {
    if (workSummaryRemote === undefined) return
    if (workSummaryRemote === null) {
      setWorkSummary(null)
      return
    }
    setWorkSummary({
      ticketId: workSummaryRemote.ticketId,
      totalWorkedMs: workSummaryRemote.totalWorkedMs ?? 0,
      internalWorkedMs: workSummaryRemote.internalWorkedMs ?? 0,
      externalWorkedMs: workSummaryRemote.externalWorkedMs ?? 0,
      activeSession: workSummaryRemote.activeSession
        ? {
            id: workSummaryRemote.activeSession.id,
            agentId: workSummaryRemote.activeSession.agentId,
            startedAt: workSummaryRemote.activeSession.startedAt,
            workType: (workSummaryRemote.activeSession.workType ?? "INTERNAL").toString().toUpperCase(),
          }
        : null,
    })
  }, [workSummaryRemote])

  const isPlaying = Boolean(workSummary?.activeSession)
  const [now, setNow] = useState(() => Date.now())
  // Guarda um marcador local do início da sessão atual para evitar inflar tempo com
  // timestamps defasados vindos da rede. Escolhemos o MAIOR entre (remoto, local).
  const localStartAtRef = useRef<number>(0)

  useEffect(() => {
    if (!workSummary?.activeSession) return
    const interval = setInterval(() => {
      setNow(Date.now())
    }, 1000)
    return () => clearInterval(interval)
  }, [workSummary?.activeSession?.id])

  // Sempre que a sessão ativa (id) mudar, sincroniza o ponteiro local
  useEffect(() => {
    if (!workSummary?.activeSession) {
      localStartAtRef.current = 0
      return
    }
    const remoteStart = Number(workSummary.activeSession.startedAt) || 0
    if (remoteStart > localStartAtRef.current) {
      localStartAtRef.current = remoteStart
    }
  }, [workSummary?.activeSession?.id, workSummary?.activeSession?.startedAt])

  useEffect(() => {
    if (!pauseDialogOpen) {
      setPauseReason(PAUSE_REASONS[0]?.value ?? "NO_CONTACT")
      setPauseNote("")
      setPausing(false)
    }
  }, [pauseDialogOpen])

  const currentSessionMs = workSummary?.activeSession
    ? (() => {
        const remoteStart = Number(workSummary.activeSession.startedAt) || 0
        const effectiveStart = Math.max(remoteStart, localStartAtRef.current || 0)
        return Math.max(0, now - effectiveStart)
      })()
    : 0
  const totalWorkedMs = workSummary ? workSummary.totalWorkedMs + currentSessionMs : 0
  const internalWorkedMs = workSummary
    ? workSummary.internalWorkedMs + (workSummary.activeSession?.workType === "INTERNAL" ? currentSessionMs : 0)
    : 0
  const externalWorkedMs = workSummary
    ? workSummary.externalWorkedMs + (workSummary.activeSession?.workType === "EXTERNAL" ? currentSessionMs : 0)
    : 0

  const formattedTotalWorked = useMemo(() => formatDuration(totalWorkedMs), [totalWorkedMs])
  const updatedRelative = useMemo(
    () => formatDistanceToNow(ticket.updatedAt, { addSuffix: true, locale: ptBR }),
    [ticket.updatedAt]
  )

  const handleStartWork = async (workType: "INTERNAL" | "EXTERNAL") => {
    if (!convexUserId) return
    toast.dismiss("work")
    toast.loading("Iniciando atendimento...", { id: "work" })
    try {
      const result = await startWork({ ticketId: ticket.id as Id<"tickets">, actorId: convexUserId as Id<"users">, workType })
      if (result?.status === "already_started") {
        toast.info("O atendimento já estava em andamento", { id: "work" })
      } else {
        toast.success("Atendimento iniciado", { id: "work" })
      }
      // Otimização local: garantir startedAt correto imediatamente
      const startedAtMs = typeof result?.startedAt === "number" ? result.startedAt : Date.now()
      localStartAtRef.current = startedAtMs
      const sessionId = (result as { sessionId?: unknown })?.sessionId as Id<"ticketWorkSessions"> | undefined
      setWorkSummary((prev) => {
        const base: WorkSummarySnapshot = prev ?? {
          ticketId: ticket.id as Id<"tickets">,
          totalWorkedMs: 0,
          internalWorkedMs: 0,
          externalWorkedMs: 0,
          activeSession: null,
        }
        return {
          ...base,
          activeSession: {
            id: (sessionId as Id<"ticketWorkSessions">) ?? (base.activeSession?.id as Id<"ticketWorkSessions">),
            agentId: convexUserId as Id<"users">,
            startedAt: startedAtMs,
            workType,
          },
        }
      })
    } catch (error) {
      const message = error instanceof Error ? error.message : "Não foi possível atualizar o atendimento"
      toast.error(message, { id: "work" })
    }
  }

  const handlePauseConfirm = async () => {
    if (!convexUserId) return
    toast.dismiss("work")
    toast.loading("Pausando atendimento...", { id: "work" })
    setPausing(true)
    try {
      const result = await pauseWork({
        ticketId: ticket.id as Id<"tickets">,
        actorId: convexUserId as Id<"users">,
        reason: pauseReason,
        note: pauseNote.trim() ? pauseNote.trim() : undefined,
      })
      if (result?.status === "already_paused") {
        toast.info("O atendimento já estava pausado", { id: "work" })
      } else {
        toast.success("Atendimento pausado", { id: "work" })
      }
      setPauseDialogOpen(false)
      // Otimização local: aplicar duração retornada no total e limpar sessão ativa
      const delta = typeof (result as { durationMs?: unknown })?.durationMs === "number" ? (result as { durationMs?: number }).durationMs! : 0
      localStartAtRef.current = 0
      setWorkSummary((prev) => {
        if (!prev) return prev
        const workType = prev.activeSession?.workType ?? "INTERNAL"
        return {
          ...prev,
          totalWorkedMs: prev.totalWorkedMs + delta,
          internalWorkedMs: prev.internalWorkedMs + (workType === "INTERNAL" ? delta : 0),
          externalWorkedMs: prev.externalWorkedMs + (workType === "EXTERNAL" ? delta : 0),
          activeSession: null,
        }
      })
    } catch (error) {
      const message = error instanceof Error ? error.message : "Não foi possível atualizar o atendimento"
      toast.error(message, { id: "work" })
    } finally {
      setPausing(false)
    }
  }

  const handleExportPdf = useCallback(async () => {
    try {
      setExportingPdf(true)
      toast.dismiss("ticket-export")
      toast.loading("Gerando PDF...", { id: "ticket-export" })
      const response = await fetch(`/api/tickets/${ticket.id}/export/pdf`, { credentials: "include" })
      if (!response.ok) {
        throw new Error(`failed: ${response.status}`)
      }
      const blob = await response.blob()
      const url = URL.createObjectURL(blob)
      const link = document.createElement("a")
      link.href = url
      link.download = `ticket-${ticket.reference}.pdf`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      toast.success("PDF exportado com sucesso!", { id: "ticket-export" })
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível exportar o PDF.", { id: "ticket-export" })
    } finally {
      setExportingPdf(false)
    }
  }, [ticket.id, ticket.reference])

  return (
    <div className={cardClass}>
      <div className="absolute right-6 top-6 flex items-center gap-3">
        {!editing ? (
          <Button size="sm" className={editButtonClass} onClick={() => setEditing(true)}>
            Editar
          </Button>
        ) : null}
        <Button
          size="icon"
          variant="outline"
          aria-label="Exportar PDF"
          className="inline-flex items-center justify-center rounded-lg border border-slate-200 bg-white text-neutral-800 hover:bg-slate-50"
          onClick={handleExportPdf}
          disabled={exportingPdf}
          title="Exportar PDF"
        >
          {exportingPdf ? <Spinner className="size-4 text-neutral-700" /> : <IconDownload className="size-5" />}
        </Button>
        {workSummary ? (
          <div className="flex items-center gap-2">
            <Badge className="inline-flex h-9 items-center gap-2 rounded-full border border-slate-200 bg-white px-3 text-sm font-semibold text-neutral-700">
              <IconClock className="size-4 text-neutral-700" /> Tempo total: {formattedTotalWorked}
            </Badge>
            <Tooltip>
              <TooltipTrigger asChild>
                <button
                  type="button"
                  className="inline-flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 bg-white text-neutral-600 transition hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#00d6eb]/30"
                  aria-label="Ver detalhamento das horas internas e externas"
                >
                  <IconInfoCircle className="size-4" />
                </button>
              </TooltipTrigger>
              <TooltipContent className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-medium text-neutral-700 shadow-lg">
                <div className="flex flex-col gap-1">
                  <span>Horas internas: {formatDuration(internalWorkedMs)}</span>
                  <span>Horas externas: {formatDuration(externalWorkedMs)}</span>
                </div>
              </TooltipContent>
            </Tooltip>
          </div>
        ) : null}
        <DeleteTicketDialog ticketId={ticket.id as Id<"tickets">} />
      </div>
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="space-y-3">
      <div className="flex flex-wrap items-center gap-3">
        <Badge className={referenceBadgeClass}>#{ticket.reference}</Badge>
        {isAvulso ? (
          <Badge className="inline-flex h-9 items-center gap-2 rounded-full border border-rose-200 bg-rose-50 px-3 text-sm font-semibold text-rose-700">
            Cliente avulso
          </Badge>
        ) : null}
        <PrioritySelect ticketId={ticket.id} value={ticket.priority} />
        <StatusSelect
          ticketId={ticket.id}
          value={status}
          tenantId={ticket.tenantId}
          requesterName={ticket.requester?.name ?? ticket.requester?.email ?? null}
        />
            {isPlaying ? (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="inline-flex">
                    <Button
                      size="sm"
                      className={pauseButtonClass}
                      onClick={() => {
                        if (!convexUserId || pauseDisabled) return
                        setPauseDialogOpen(true)
                      }}
                      disabled={pauseDisabled}
                    >
                      <IconPlayerPause className="size-4 text-white" /> Pausar
                    </Button>
                  </span>
                </TooltipTrigger>
                {pauseDisabled ? (
                  <TooltipContent className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-medium text-neutral-700 shadow-lg">
                    Apenas o responsável atual ou um administrador pode pausar o atendimento.
                  </TooltipContent>
                ) : null}
              </Tooltip>
            ) : startDisabled ? (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="inline-flex">
                    <Button size="sm" className={startButtonClass} disabled>
                      <IconPlayerPlay className="size-4 text-white" /> Iniciar
                    </Button>
                  </span>
                </TooltipTrigger>
                <TooltipContent className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-medium text-neutral-700 shadow-lg">
                  Apenas o responsável atual ou um administrador pode iniciar este atendimento.
                </TooltipContent>
              </Tooltip>
            ) : (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button size="sm" className={startButtonClass}>
                    <IconPlayerPlay className="size-4 text-white" /> Iniciar
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="start" className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
                  <DropdownMenuItem onSelect={() => void handleStartWork("INTERNAL")}>Iniciar (interno)</DropdownMenuItem>
                  <DropdownMenuItem onSelect={() => void handleStartWork("EXTERNAL")}>Iniciar (externo)</DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            )}
          </div>
          {editing ? (
            <div className="space-y-2">
              <Input
                value={subject}
                onChange={(e) => setSubject(e.target.value)}
                className="h-10 rounded-lg border border-slate-300 text-lg font-semibold text-neutral-900"
              />
              <textarea
                value={summary}
                onChange={(e) => setSummary(e.target.value)}
                rows={3}
                className="w-full rounded-lg border border-slate-300 bg-white p-3 text-sm text-neutral-800 shadow-sm"
                placeholder="Adicione um resumo opcional"
              />
            </div>
          ) : (
            <div className="space-y-1">
              <h1 className="break-words text-2xl font-semibold text-neutral-900">{subject}</h1>
              {summary ? <p className="max-w-2xl text-sm text-neutral-600">{summary}</p> : null}
            </div>
          )}
        </div>
      </div>
      <Separator className="bg-slate-200" />
      <div className="grid gap-4 text-sm text-neutral-600 sm:grid-cols-2 lg:grid-cols-3">
        <div className="flex flex-col gap-1">
          <span className={sectionLabelClass}>Categoria primária</span>
          {editing ? (
            <Select
              disabled={saving || categoriesLoading || isManager}
              value={selectedCategoryId ? selectedCategoryId : EMPTY_CATEGORY_VALUE}
              onValueChange={(value) => {
                if (isManager) return
                if (value === EMPTY_CATEGORY_VALUE) {
                  setCategorySelection({ categoryId: "", subcategoryId: "" })
                  return
                }
                const category = categories.find((item) => item.id === value)
                setCategorySelection({
                  categoryId: value,
                  subcategoryId: category?.secondary.find((option) => option.id === selectedSubcategoryId)?.id ?? "",
                })
              }}
            >
              <SelectTrigger className={selectTriggerClass}>
                <SelectValue placeholder={categoriesLoading ? "Carregando..." : "Sem categoria"} />
              </SelectTrigger>
              <SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
                <SelectItem value={EMPTY_CATEGORY_VALUE}>Sem categoria</SelectItem>
                {categories.map((category) => (
                  <SelectItem key={category.id} value={category.id}>
                    {category.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          ) : (
            <span className={sectionValueClass}>{ticket.category?.name ?? "Sem categoria"}</span>
          )}
        </div>
        <div className="flex flex-col gap-1">
          <span className={sectionLabelClass}>Categoria secundária</span>
          {editing ? (
            <Select
              disabled={
                saving || categoriesLoading || !selectedCategoryId || isManager
              }
              value={selectedSubcategoryId ? selectedSubcategoryId : EMPTY_SUBCATEGORY_VALUE}
              onValueChange={(value) => {
                if (isManager) return
                if (value === EMPTY_SUBCATEGORY_VALUE) {
                  setCategorySelection((prev) => ({ ...prev, subcategoryId: "" }))
                  return
                }
                setCategorySelection((prev) => ({ ...prev, subcategoryId: value }))
              }}
            >
              <SelectTrigger className={selectTriggerClass}>
                <SelectValue
                  placeholder={
                    !selectedCategoryId
                      ? "Selecione uma primária"
                      : secondaryOptions.length === 0
                        ? "Sem subcategoria"
                        : "Selecionar"
                  }
                />
              </SelectTrigger>
              <SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
                <SelectItem value={EMPTY_SUBCATEGORY_VALUE}>Sem subcategoria</SelectItem>
                {secondaryOptions.map((option) => (
                  <SelectItem key={option.id} value={option.id}>
                    {option.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          ) : (
            <span className={sectionValueClass}>{ticket.subcategory?.name ?? "Sem subcategoria"}</span>
          )}
        </div>
        <div className="flex flex-col gap-1">
          <span className={sectionLabelClass}>Fila</span>
          {editing ? (
            <Select
              disabled={isManager}
              value={queueSelection}
              onValueChange={(value) => {
                if (isManager) return
                setQueueSelection(value)
              }}
            >
              <SelectTrigger className={smallSelectTriggerClass}>
                <SelectValue placeholder="Selecionar" />
              </SelectTrigger>
              <SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
                {queues.map((queue) => (
                  <SelectItem key={queue.id} value={queue.name}>
                    {queue.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          ) : (
            <span className={sectionValueClass}>{ticket.queue ?? "Sem fila"}</span>
          )}
        </div>
        <div className="flex flex-col gap-1">
          <span className={sectionLabelClass}>Solicitante</span>
          <span className={sectionValueClass}>{ticket.requester.name}</span>
        </div>
        <div className="flex flex-col gap-1">
          <span className={sectionLabelClass}>Empresa</span>
          <span className={sectionValueClass}>{companyLabel}</span>
        </div>
        <div className="flex flex-col gap-1">
          <span className={sectionLabelClass}>Responsável</span>
          {editing ? (
            <Select
              disabled={isManager}
              value={assigneeSelection}
              onValueChange={(value) => {
                if (isManager) return
                setAssigneeSelection(value)
              }}
            >
              <SelectTrigger className={selectTriggerClass}>
                <SelectValue placeholder="Selecionar" />
              </SelectTrigger>
              <SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
                {agents.map((agent) => (
                  <SelectItem key={agent._id} value={agent._id}>
                    {agent.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          ) : (
            <span className={sectionValueClass}>{ticket.assignee?.name ?? "Não atribuído"}</span>
          )}
        </div>
        <div className="flex flex-col gap-1">
          <span className={sectionLabelClass}>Criado em</span>
          <span className={sectionValueClass}>{format(ticket.createdAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}</span>
        </div>
        <div className="flex flex-col gap-1">
          <span className={sectionLabelClass}>Atualizado em</span>
          <div className="flex items-center gap-2">
            <span className={sectionValueClass}>{format(ticket.updatedAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}</span>
            <span className={subtleBadgeClass}>{updatedRelative}</span>
          </div>
        </div>
        {ticket.dueAt ? (
          <div className="flex flex-col gap-1">
            <span className={sectionLabelClass}>SLA até</span>
            <span className={sectionValueClass}>{format(ticket.dueAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}</span>
          </div>
        ) : null}
        {ticket.slaPolicy ? (
          <div className="flex flex-col gap-1">
            <span className={sectionLabelClass}>Política</span>
            <span className={sectionValueClass}>{ticket.slaPolicy.name}</span>
          </div>
        ) : null}
        {editing ? (
          <div className="flex items-center justify-end gap-2 sm:col-span-2 lg:col-span-3">
            <Button variant="ghost" size="sm" className="text-sm font-semibold text-neutral-700" onClick={handleCancel}>
              Cancelar
            </Button>
            <Button size="sm" className={startButtonClass} onClick={handleSave} disabled={!formDirty || saving}>
              Salvar
            </Button>
          </div>
        ) : null}
      </div>
      <Dialog open={pauseDialogOpen} onOpenChange={setPauseDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Registrar pausa</DialogTitle>
            <DialogDescription>Informe o motivo da pausa para registrar no histórico do chamado.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-1.5">
              <span className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Motivo</span>
              <Select value={pauseReason} onValueChange={setPauseReason}>
                <SelectTrigger className={selectTriggerClass}>
                  <SelectValue placeholder="Selecione" />
                </SelectTrigger>
                <SelectContent className="rounded-lg border border-slate-200 bg-white text-neutral-800 shadow-sm">
                  {PAUSE_REASONS.map((reason) => (
                    <SelectItem key={reason.value} value={reason.value}>
                      {reason.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <span className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Observações</span>
              <Textarea
                value={pauseNote}
                onChange={(event) => setPauseNote(event.target.value)}
                rows={3}
                placeholder="Adicione detalhes opcionais (visível apenas internamente)."
                className="min-h-[96px]"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setPauseDialogOpen(false)} disabled={pausing}>
              Cancelar
            </Button>
            <Button
              className={pauseButtonClass}
              onClick={handlePauseConfirm}
              disabled={pausing || !pauseReason}
            >
              {pausing ? <Spinner className="size-4 text-white" /> : "Registrar pausa"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
