import { addMinutes, subHours, subMinutes } from "date-fns"
import { z } from "zod"

import {
  commentVisibilitySchema,
  ticketChannelSchema,
  ticketPrioritySchema,
  ticketSchema,
  ticketStatusSchema,
  ticketWithDetailsSchema,
  ticketPlayContextSchema,
  ticketQueueSummarySchema,
} from "@/lib/schemas/ticket"

const tenantId = "tenant-atlas"

type UserRecord = z.infer<typeof ticketSchema>["requester"]

const users: Record<string, UserRecord> = {
  rever: {
    id: "user-rever",
    name: "Rever",
    email: "renan.pac@paulicon.com.br",
    avatarUrl: "https://avatar.vercel.sh/rever",
    teams: ["Chamados"],
  },
  carla: {
    id: "user-carla",
    name: "Carla Menezes",
    email: "carla.menezes@example.com",
    avatarUrl: "https://avatar.vercel.sh/carla",
    teams: ["Laboratório"],
  },
  diego: {
    id: "user-diego",
    name: "Diego Ramos",
    email: "diego.ramos@example.com",
    avatarUrl: "https://avatar.vercel.sh/diego",
    teams: ["Field Services"],
  },
  eduarda: {
    id: "user-eduarda",
    name: "Eduarda Rocha",
    email: "eduarda.rocha@example.com",
    avatarUrl: "https://avatar.vercel.sh/eduarda",
    teams: ["Clientes"],
  },
}

const queues = [
  { id: "queue-chamados", name: "Chamados", pending: 18, waiting: 4, breached: 2 },
  { id: "queue-laboratorio", name: "Laboratório", pending: 9, waiting: 3, breached: 1 },
  { id: "queue-field", name: "Field Services", pending: 5, waiting: 2, breached: 0 },
]

const baseTickets = [
  {
    id: "ticket-1001",
    tenantId,
    reference: 41001,
    subject: "Erro 500 ao acessar portal do cliente",
    summary: "Clientes relatam erro intermitente no portal web",
    status: ticketStatusSchema.enum.AWAITING_ATTENDANCE,
    priority: ticketPrioritySchema.enum.URGENT,
    channel: ticketChannelSchema.enum.EMAIL,
    queue: "Chamados",
    requester: users.eduarda,
    assignee: users.rever,
    slaPolicy: {
      id: "sla-critical",
      name: "SLA Crítico",
      targetMinutesToFirstResponse: 15,
      targetMinutesToResolution: 240,
    },
    dueAt: addMinutes(new Date(), 120),
    firstResponseAt: subMinutes(new Date(), 20),
    resolvedAt: null,
    updatedAt: subMinutes(new Date(), 10),
    createdAt: subHours(new Date(), 5),
    tags: ["portal", "cliente"],
    lastTimelineEntry: "Prioridade atualizada para URGENT por Rever",
    metrics: {
      timeWaitingMinutes: 12,
      timeOpenedMinutes: 300,
    },
  },
  {
    id: "ticket-1002",
    tenantId,
    reference: 41002,
    subject: "Integração ERP parada",
    summary: "Webhook do ERP retornando timeout",
    status: ticketStatusSchema.enum.PAUSED,
    priority: ticketPrioritySchema.enum.HIGH,
    channel: ticketChannelSchema.enum.WHATSAPP,
    queue: "Laboratório",
    requester: users.eduarda,
    assignee: users.carla,
    slaPolicy: {
      id: "sla-priority",
      name: "SLA Prioritário",
      targetMinutesToFirstResponse: 30,
      targetMinutesToResolution: 360,
    },
    dueAt: addMinutes(new Date(), 240),
    firstResponseAt: subMinutes(new Date(), 60),
    resolvedAt: null,
    updatedAt: subMinutes(new Date(), 30),
    createdAt: subHours(new Date(), 8),
    tags: ["Integração", "erp"],
    lastTimelineEntry: "Aguardando retorno do fornecedor externo",
    metrics: {
      timeWaitingMinutes: 90,
      timeOpenedMinutes: 420,
    },
  },
  {
    id: "ticket-1003",
    tenantId,
    reference: 41003,
    subject: "Solicitação de acesso VPN",
    summary: "Novo colaborador precisa de acesso",
    status: ticketStatusSchema.enum.PENDING,
    priority: ticketPrioritySchema.enum.MEDIUM,
    channel: ticketChannelSchema.enum.MANUAL,
    queue: "Field Services",
    requester: users.eduarda,
    assignee: null,
    slaPolicy: null,
    dueAt: null,
    firstResponseAt: null,
    resolvedAt: null,
    updatedAt: subHours(new Date(), 1),
    createdAt: subHours(new Date(), 1),
    tags: ["vpn"],
    metrics: null,
  },
  {
    id: "ticket-1004",
    tenantId,
    reference: 41004,
    subject: "Bug no app mobile - upload de foto",
    summary: "Upload trava com arquivos acima de 5MB",
    status: ticketStatusSchema.enum.PAUSED,
    priority: ticketPrioritySchema.enum.HIGH,
    channel: ticketChannelSchema.enum.CHAT,
    queue: "Laboratório",
    requester: users.eduarda,
    assignee: users.carla,
    slaPolicy: {
      id: "sla-standard",
      name: "SLA Padrão",
      targetMinutesToFirstResponse: 60,
      targetMinutesToResolution: 720,
    },
    dueAt: addMinutes(new Date(), 360),
    firstResponseAt: subMinutes(new Date(), 50),
    resolvedAt: null,
    updatedAt: subMinutes(new Date(), 90),
    createdAt: subHours(new Date(), 12),
    tags: ["mobile", "upload"],
    lastTimelineEntry: "Ticket pausado aguardando logs do time Mobile",
    metrics: {
      timeWaitingMinutes: 180,
      timeOpenedMinutes: 720,
    },
  },
  {
    id: "ticket-1005",
    tenantId,
    reference: 41005,
    subject: "Reclamação de cobranca duplicada",
    summary: "Cliente recebeu boleto duplicado",
    status: ticketStatusSchema.enum.RESOLVED,
    priority: ticketPrioritySchema.enum.MEDIUM,
    channel: ticketChannelSchema.enum.EMAIL,
    queue: "Chamados",
    requester: users.eduarda,
    assignee: users.rever,
    slaPolicy: {
      id: "sla-standard",
      name: "SLA Padrão",
      targetMinutesToFirstResponse: 60,
      targetMinutesToResolution: 720,
    },
    dueAt: null,
    firstResponseAt: subMinutes(new Date(), 80),
    resolvedAt: subMinutes(new Date(), 10),
    updatedAt: subMinutes(new Date(), 5),
    createdAt: subHours(new Date(), 20),
    tags: ["financeiro"],
    lastTimelineEntry: "Ticket resolvido, aguardando confirmação do cliente",
    metrics: {
      timeWaitingMinutes: 30,
      timeOpenedMinutes: 1100,
    },
  },
]

export const tickets = baseTickets as Array<z.infer<typeof ticketSchema>>

const commentsByTicket: Record<string, z.infer<typeof ticketWithDetailsSchema>["comments"]> = {
  "ticket-1001": [
    {
      id: "comment-1",
      author: users.rever,
      visibility: commentVisibilitySchema.enum.INTERNAL,
      body: "Logs coletados e enviados para o time de infraestrutura.",
      attachments: [],
      createdAt: subMinutes(new Date(), 40),
      updatedAt: subMinutes(new Date(), 40),
    },
    {
      id: "comment-2",
      author: users.rever,
      visibility: commentVisibilitySchema.enum.PUBLIC,
      body: "Estamos investigando o incidente, retorno em 30 minutos.",
      attachments: [],
      createdAt: subMinutes(new Date(), 25),
      updatedAt: subMinutes(new Date(), 25),
    },
  ],
  "ticket-1002": [
    {
      id: "comment-3",
      author: users.carla,
      visibility: commentVisibilitySchema.enum.INTERNAL,
      body: "Contato realizado com fornecedor, aguardando confirmação.",
      attachments: [],
      createdAt: subMinutes(new Date(), 70),
      updatedAt: subMinutes(new Date(), 70),
    },
  ],
}

const timelineByTicket: Record<string, z.infer<typeof ticketWithDetailsSchema>["timeline"]> = {
  "ticket-1001": [
    {
      id: "timeline-1",
      type: "STATUS_CHANGED",
      payload: { from: "PENDING", to: "AWAITING_ATTENDANCE" },
      createdAt: subHours(new Date(), 5),
    },
    {
      id: "timeline-2",
      type: "ASSIGNEE_CHANGED",
        payload: { assignee: users.rever.name },
      createdAt: subHours(new Date(), 4),
    },
    {
      id: "timeline-3",
      type: "COMMENT_ADDED",
        payload: { author: users.rever.name },
      createdAt: subHours(new Date(), 1),
    },
  ],
  "ticket-1002": [
    {
      id: "timeline-4",
      type: "STATUS_CHANGED",
      payload: { from: "AWAITING_ATTENDANCE", to: "PAUSED" },
      createdAt: subHours(new Date(), 3),
    },
  ],
}

export const ticketDetails = tickets.map((ticket) => ({
  ...ticket,
  description:
    "Incidente reportado automaticamente pelo monitoramento. Logs indicam aumento de latência em chamadas ao servico de autenticação.",
  customFields: {
    ambiente: { label: "Ambiente", type: "select", value: "producao", displayValue: "Produção" },
    categoria: { label: "Categoria", type: "text", value: "Incidente" },
    impacto: { label: "Impacto", type: "select", value: "alto", displayValue: "Alto" },
  },
  timeline:
    timelineByTicket[ticket.id] ??
    ([
      {
        id: `timeline-${ticket.id}`,
        type: "CREATED",
        createdAt: ticket.createdAt,
        payload: { requester: ticket.requester.name },
      },
    ] as z.infer<typeof ticketWithDetailsSchema>["timeline"]),
  comments: commentsByTicket[ticket.id] ?? [],
})) as Array<z.infer<typeof ticketWithDetailsSchema>>

export function getTicketById(id: string) {
  return ticketDetails.find((ticket) => ticket.id === id)
}

export const queueSummaries = queues as Array<z.infer<typeof ticketQueueSummarySchema>>

export const playContext = {
  queue: queueSummaries[0],
  nextTicket:
    tickets.find(
      (ticket) =>
        ticket.status !== ticketStatusSchema.enum.RESOLVED
    ) ?? null,
} as z.infer<typeof ticketPlayContextSchema>


