import { useMemo } from "react"
import { format } from "date-fns"
import { ptBR } from "date-fns/locale"

import type { TicketWithDetails } from "@/lib/schemas/ticket"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { getTicketStatusLabel, getTicketStatusSummaryTone } from "@/lib/ticket-status-style"
import { Badge } from "@/components/ui/badge"
import { cn } from "@/lib/utils"

interface TicketDetailsPanelProps {
  ticket: TicketWithDetails
}

type SummaryTone = "default" | "info" | "warning" | "success" | "muted" | "danger" | "primary"

const priorityLabel: Record<TicketWithDetails["priority"], string> = {
  LOW: "Baixa",
  MEDIUM: "Média",
  HIGH: "Alta",
  URGENT: "Urgente",
}

const priorityTone: Record<TicketWithDetails["priority"], SummaryTone> = {
  LOW: "muted",
  MEDIUM: "info",
  HIGH: "warning",
  URGENT: "danger",
}

function formatDuration(ms?: number | null) {
  if (!ms || ms <= 0) return "0s"
  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 formatMinutes(value?: number | null) {
  if (value === null || value === undefined) return "—"
  return `${value} min`
}

type SummaryChipConfig = {
  key: string
  label: string
  value: string
  tone: SummaryTone
  labelClassName?: string
}

export function TicketDetailsPanel({ ticket }: TicketDetailsPanelProps) {
  const isAvulso = Boolean(ticket.company?.isAvulso)
  const companyLabel = ticket.company?.name ?? (isAvulso ? "Cliente avulso" : "Sem empresa vinculada")

  const summaryChips = useMemo(() => {
    const chips: SummaryChipConfig[] = [
      {
        key: "queue",
        label: "Fila",
        value: ticket.queue ?? "Sem fila",
        tone: ticket.queue ? "default" : "muted",
      },
      {
        key: "company",
        label: "Empresa",
        value: companyLabel,
        tone: isAvulso ? "warning" : "default",
      },
      {
        key: "status",
        label: "Status",
        value: getTicketStatusLabel(ticket.status) ?? ticket.status,
        tone: getTicketStatusSummaryTone(ticket.status) as SummaryTone,
      },
      {
        key: "priority",
        label: "Prioridade",
        value: priorityLabel[ticket.priority] ?? ticket.priority,
        tone: priorityTone[ticket.priority] ?? "default",
      },
      {
        key: "assignee",
        label: "Responsável",
        value: ticket.assignee?.name ?? "Não atribuído",
        tone: ticket.assignee ? "default" : "muted",
      },
    ]
    if (ticket.formTemplateLabel) {
      chips.splice(Math.min(chips.length, 5), 0, {
        key: "formTemplate",
        label: "Fluxo",
        value: ticket.formTemplateLabel,
        tone: "primary",
        labelClassName: "text-white",
      })
    }
    return chips
  }, [companyLabel, isAvulso, ticket.assignee, ticket.formTemplateLabel, ticket.priority, ticket.queue, ticket.status])

  const agentTotals = useMemo(() => {
    const totals = ticket.workSummary?.perAgentTotals ?? []
    return totals
      .map((item) => ({
        agentId: String(item.agentId),
        agentName: item.agentName ?? null,
        totalWorkedMs: item.totalWorkedMs ?? 0,
        internalWorkedMs: item.internalWorkedMs ?? 0,
        externalWorkedMs: item.externalWorkedMs ?? 0,
      }))
      .sort((a, b) => b.totalWorkedMs - a.totalWorkedMs)
  }, [ticket.workSummary?.perAgentTotals])

  return (
    <Card className="rounded-2xl border border-slate-200 bg-white shadow-sm">
      <CardHeader className="px-4 pb-3">
        <div className="flex items-start justify-between gap-3">
          <div className="space-y-1">
            <CardTitle className="text-lg font-semibold text-neutral-900">Detalhes</CardTitle>
            <CardDescription className="text-sm text-neutral-500">
              Resumo do ticket, métricas de SLA, tempo dedicado e campos personalizados.
            </CardDescription>
          </div>
          {isAvulso ? (
            <Badge className="h-7 rounded-full border border-amber-200 bg-amber-50 px-3 text-xs font-semibold uppercase tracking-wide text-amber-700">
              Cliente avulso
            </Badge>
          ) : null}
        </div>
      </CardHeader>
      <CardContent className="space-y-6 px-4 pb-6">
        <section className="space-y-3">
          <h3 className="text-sm font-semibold text-neutral-900">Resumo</h3>
          <div className="grid gap-3 sm:grid-cols-2">
            {summaryChips.map(({ key, label, value, tone, labelClassName }) => (
              <SummaryChip key={key} label={label} value={value} tone={tone} labelClassName={labelClassName} />
            ))}
          </div>
        </section>

        <section className="space-y-3">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <h3 className="text-sm font-semibold text-neutral-900">SLA & métricas</h3>
            {ticket.slaPolicy ? (
              <span className="text-xs font-medium text-neutral-500">{ticket.slaPolicy.name}</span>
            ) : null}
          </div>
          <div className="grid gap-3 md:grid-cols-2">
            <div className="rounded-2xl border border-slate-200 bg-white px-4 py-3 shadow-sm">
              <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Política de SLA</p>
              {ticket.slaPolicy ? (
                <div className="mt-3 space-y-2 text-sm text-neutral-700">
                  <div className="flex items-center justify-between gap-4">
                    <span className="text-xs text-neutral-500">Resposta inicial</span>
                    <span className="text-sm font-semibold text-neutral-900">
                      {formatMinutes(ticket.slaPolicy.targetMinutesToFirstResponse)}
                    </span>
                  </div>
                  <div className="flex items-center justify-between gap-4">
                    <span className="text-xs text-neutral-500">Resolução</span>
                    <span className="text-sm font-semibold text-neutral-900">
                      {formatMinutes(ticket.slaPolicy.targetMinutesToResolution)}
                    </span>
                  </div>
                </div>
              ) : (
                <p className="mt-3 text-sm text-neutral-600">Sem política de SLA atribuída.</p>
              )}
            </div>
            <div className="rounded-2xl border border-slate-200 bg-white px-4 py-3 shadow-sm">
              <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Métricas</p>
              {ticket.metrics ? (
                <div className="mt-3 space-y-2 text-sm text-neutral-700">
                  <div className="flex items-center justify-between gap-4">
                    <span className="text-xs text-neutral-500">Tempo aguardando</span>
                    <span className="text-sm font-semibold text-neutral-900">
                      {formatMinutes(ticket.metrics.timeWaitingMinutes)}
                    </span>
                  </div>
                  <div className="flex items-center justify-between gap-4">
                    <span className="text-xs text-neutral-500">Tempo aberto</span>
                    <span className="text-sm font-semibold text-neutral-900">
                      {formatMinutes(ticket.metrics.timeOpenedMinutes)}
                    </span>
                  </div>
                </div>
              ) : (
                <p className="mt-3 text-sm text-neutral-600">Sem dados registrados ainda.</p>
              )}
            </div>
          </div>
        </section>

        <section className="space-y-3">
          <h3 className="text-sm font-semibold text-neutral-900">Tempo por agente</h3>
          {agentTotals.length > 0 ? (
            <div className="grid gap-2">
              {agentTotals.map((agent) => (
                <div
                  key={agent.agentId}
                  className="rounded-2xl border border-slate-200 bg-white px-4 py-3 shadow-sm"
                >
                  <div className="flex items-center justify-between gap-4">
                    <span className="text-sm font-semibold text-neutral-900">
                      {agent.agentName ?? "Agente removido"}
                    </span>
                    <span className="text-sm font-semibold text-neutral-900">
                      {formatDuration(agent.totalWorkedMs)}
                    </span>
                  </div>
                  <div className="mt-2 flex flex-wrap gap-4 text-xs text-neutral-500">
                    <span>
                      Interno:{" "}
                      <span className="font-medium text-neutral-800">{formatDuration(agent.internalWorkedMs)}</span>
                    </span>
                    <span>
                      Externo:{" "}
                      <span className="font-medium text-neutral-800">{formatDuration(agent.externalWorkedMs)}</span>
                    </span>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-sm text-neutral-600">Nenhum tempo registrado neste ticket ainda.</p>
          )}
        </section>

        <section className="space-y-3">
          <h3 className="text-sm font-semibold text-neutral-900">Histórico</h3>
          <div className="rounded-2xl border border-slate-200 bg-white px-4 py-3 shadow-sm text-sm text-neutral-700">
            <div className="flex items-center justify-between gap-4 border-b border-slate-100 pb-2">
              <span className="text-xs uppercase tracking-wide text-neutral-500">Criado em</span>
              <span className="font-semibold text-neutral-900">
                {format(ticket.createdAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}
              </span>
            </div>
            <div className="flex items-center justify-between gap-4 border-b border-slate-100 py-2">
              <span className="text-xs uppercase tracking-wide text-neutral-500">Atualizado em</span>
              <span className="font-semibold text-neutral-900">
                {format(ticket.updatedAt, "dd/MM/yyyy HH:mm", { locale: ptBR })}
              </span>
            </div>
            <div className="flex items-center justify-between gap-4 pt-2">
              <span className="text-xs uppercase tracking-wide text-neutral-500">Resolvido em</span>
              <span className="font-semibold text-neutral-900">
                {ticket.resolvedAt ? format(ticket.resolvedAt, "dd/MM/yyyy HH:mm", { locale: ptBR }) : "—"}
              </span>
            </div>
          </div>
        </section>
      </CardContent>
    </Card>
  )
}

function SummaryChip({
  label,
  value,
  tone = "default",
  labelClassName,
}: {
  label: string
  value: string
  tone?: SummaryTone
  labelClassName?: string
}) {
  const toneClasses: Record<SummaryTone, string> = {
    default: "border-slate-200 bg-white text-neutral-900",
    info: "border-sky-200 bg-sky-50 text-sky-900",
    warning: "border-amber-200 bg-amber-50 text-amber-800",
    success: "border-emerald-200 bg-emerald-50 text-emerald-800",
    muted: "border-slate-200 bg-slate-50 text-neutral-600",
    danger: "border-rose-200 bg-rose-50 text-rose-700",
    primary: "border-black bg-black text-white",
  }

  return (
    <div className={cn("rounded-xl border px-3 py-2 shadow-sm", toneClasses[tone])}>
      <p className={cn("text-[11px] font-semibold uppercase tracking-wide text-neutral-500", labelClassName)}>{label}</p>
      <p className="mt-1 truncate text-sm font-semibold text-current">{value}</p>
    </div>
  )
}
