"use client"

import { useState } from "react"
import { format } from "date-fns"
import { ptBR } from "date-fns/locale"
import { IconClock, IconUserCircle } from "@tabler/icons-react"
import { useMutation } from "convex/react"
import { toast } from "sonner"
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { api } from "../../../convex/_generated/api"

import { useAuth } from "@/lib/auth-client"
import type { TicketWithDetails } from "@/lib/schemas/ticket"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { TicketPriorityPill } from "@/components/tickets/priority-pill"
import { TicketStatusBadge } from "@/components/tickets/status-badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

interface TicketHeaderProps {
  ticket: TicketWithDetails
}

export function TicketSummaryHeader({ ticket }: TicketHeaderProps) {
  const { userId } = useAuth()
  const updateStatus = useMutation(api.tickets.updateStatus)
  const [status, setStatus] = useState(ticket.status)
  const statusPt: Record<string, string> = {
    NEW: "Novo",
    OPEN: "Aberto",
    PENDING: "Pendente",
    ON_HOLD: "Em espera",
    RESOLVED: "Resolvido",
    CLOSED: "Fechado",
  }
  return (
    <div className="space-y-4 rounded-xl border bg-card p-6 shadow-sm">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="space-y-2">
          <div className="flex items-center gap-3">
            <Badge variant="outline" className="rounded-full px-3 py-1 text-xs uppercase tracking-wide">
              #{ticket.reference}
            </Badge>
            <TicketPriorityPill priority={ticket.priority} />
            <TicketStatusBadge status={status as any} />
            <Select
              value={status}
              onValueChange={async (value) => {
                const prev = status
                setStatus(value) // otimista
                if (!userId) return
                toast.loading("Atualizando status…", { id: "status" })
                try {
                  await updateStatus({ ticketId: ticket.id as any, status: value as any, actorId: userId as any })
                  toast.success(`Status alterado para ${statusPt[value]}.`, { id: "status" })
                } catch (e) {
                  setStatus(prev)
                  toast.error("Não foi possível alterar o status.", { id: "status" })
                }
              }}
            >
              <SelectTrigger className="h-8 w-[150px]">
                <SelectValue placeholder="Alterar status" />
              </SelectTrigger>
              <SelectContent>
                {(["NEW","OPEN","PENDING","ON_HOLD","RESOLVED","CLOSED"]).map((s) => (
                  <SelectItem key={s} value={s}>{statusPt[s]}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <h1 className="text-2xl font-semibold text-foreground">{ticket.subject}</h1>
          <p className="max-w-2xl text-sm text-muted-foreground">{ticket.summary}</p>
        </div>
      </div>
      <Separator />
      <div className="grid gap-4 text-sm text-muted-foreground sm:grid-cols-2 lg:grid-cols-3">
        <div className="flex items-center gap-2">
          <IconUserCircle className="size-4" />
          Solicitante:
          <span className="font-medium text-foreground">{ticket.requester.name}</span>
        </div>
        <div className="flex items-center gap-2">
          <IconUserCircle className="size-4" />
          Responsavel:
          <span className="font-medium text-foreground">
            {ticket.assignee?.name ?? "Aguardando atribuicao"}
          </span>
        </div>
        <div className="flex items-center gap-2">
          <IconClock className="size-4" />
          Atualizado em:
          <span className="font-medium text-foreground">
            {format(ticket.updatedAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}
          </span>
        </div>
        <div className="flex items-center gap-2">
          <IconClock className="size-4" />
          Criado em:
          <span className="font-medium text-foreground">
            {format(ticket.createdAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}
          </span>
        </div>
        {ticket.dueAt ? (
          <div className="flex items-center gap-2">
            <IconClock className="size-4" />
            SLA ate:
            <span className="font-medium text-foreground">
              {format(ticket.dueAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}
            </span>
          </div>
        ) : null}
        {ticket.slaPolicy ? (
          <div className="flex items-center gap-2">
            <IconClock className="size-4" />
            Politica:
            <span className="font-medium text-foreground">{ticket.slaPolicy.name}</span>
          </div>
        ) : null}
      </div>
    </div>
  )
}
