import { format, parse } from "date-fns"
import { ptBR } from "date-fns/locale"

export type TicketCustomFieldRecord = Record<
  string,
  {
    label: string
    type: string
    value?: unknown
    displayValue?: string
  }
>

export type TicketCustomFieldEntry = {
  key: string
  label: string
  type: string
  value: unknown
  displayValue?: string
  formattedValue: string
}

function formatBoolean(value: unknown): string {
  if (value === null || value === undefined) return "—"
  return value === true || String(value).toLowerCase() === "true" ? "Sim" : "Não"
}

const DATE_ONLY_REGEX = /^\d{4}-\d{2}-\d{2}$/

function normalizeIsoDate(value: unknown): string | null {
  if (value === null || value === undefined) return null
  if (typeof value === "string") {
    const trimmed = value.trim()
    if (!trimmed) return null
    if (DATE_ONLY_REGEX.test(trimmed)) {
      return trimmed
    }
    const parsed = new Date(trimmed)
    if (Number.isNaN(parsed.getTime())) {
      return null
    }
    return parsed.toISOString().slice(0, 10)
  }
  const date =
    value instanceof Date
      ? value
      : typeof value === "number" && Number.isFinite(value)
        ? new Date(value)
        : null
  if (!date || Number.isNaN(date.getTime())) {
    return null
  }
  return date.toISOString().slice(0, 10)
}

function formatDate(value: unknown): string {
  if (value === null || value === undefined) return "—"
  const iso = normalizeIsoDate(value)
  if (!iso) return "—"
  const parsed = parse(iso, "yyyy-MM-dd", new Date())
  if (Number.isNaN(parsed.getTime())) return "—"
  return format(parsed, "dd/MM/yyyy", { locale: ptBR })
}

function formatNumber(value: unknown): string {
  if (value === null || value === undefined || value === "") return "—"
  const numeric = typeof value === "number" ? value : Number(String(value).replace(",", "."))
  if (!Number.isFinite(numeric)) return String(value)
  return new Intl.NumberFormat("pt-BR", { maximumFractionDigits: 2 }).format(numeric)
}

function formatFallback(value: unknown): string {
  if (value === null || value === undefined) return "—"
  if (typeof value === "string" && value.trim().length === 0) return "—"
  return String(value)
}

export function formatTicketCustomFieldValue(entry: {
  type: string
  value?: unknown
  displayValue?: string
}): string {
  if (entry.displayValue && entry.displayValue.trim().length > 0) {
    return entry.displayValue
  }
  switch ((entry.type ?? "").toLowerCase()) {
    case "boolean":
      return formatBoolean(entry.value)
    case "date":
      return formatDate(entry.value)
    case "number":
      return formatNumber(entry.value)
    default:
      return formatFallback(entry.value)
  }
}

export function mapTicketCustomFields(
  record: TicketCustomFieldRecord | undefined | null
): TicketCustomFieldEntry[] {
  if (!record) return []
  return Object.entries(record)
    .map(([key, field]) => ({
      key,
      label: field.label,
      type: field.type,
      value: field.value ?? null,
      displayValue: field.displayValue,
      formattedValue: formatTicketCustomFieldValue(field),
    }))
    .sort((a, b) => a.label.localeCompare(b.label, "pt-BR"))
}
