import dayjs, { type Dayjs } from "dayjs"
import localizedFormat from "dayjs/plugin/localizedFormat"
import relativeTime from "dayjs/plugin/relativeTime"
import updateLocale from "dayjs/plugin/updateLocale"
import "dayjs/locale/fr"
import "dayjs/locale/en"

dayjs.extend(localizedFormat)
dayjs.extend(relativeTime)
dayjs.extend(updateLocale)

/** Compact relative units for list column (fr). */
dayjs.updateLocale("fr", {
  relativeTime: {
    future: "dans %s",
    past: "il y a %s",
    s: "1 min",
    m: "1 min",
    mm: "%d min",
    h: "1 h",
    hh: "%d h",
    d: "1 j",
    dd: "%d j",
    M: "1 mois",
    MM: "%d mois",
    y: "1 an",
    yy: "%d ans",
  },
})

dayjs.updateLocale("en", {
  relativeTime: {
    future: "in %s",
    past: "%s ago",
    s: "1 min",
    m: "1 min",
    mm: "%d min",
    h: "1 h",
    hh: "%d h",
    d: "1 d",
    dd: "%d d",
    M: "1 mo",
    MM: "%d mo",
    y: "1 y",
    yy: "%d y",
  },
})

const SUPPORTED_LOCALES = new Set(["fr", "en", "de", "es", "it", "pt", "nl", "pl", "ja", "zh"])

let activeLocale: string | null = null

export function resolveDriveDateLocale(): string {
  if (typeof navigator === "undefined") return "fr"
  const base = navigator.language.split("-")[0]?.toLowerCase() ?? "fr"
  return SUPPORTED_LOCALES.has(base) ? base : "en"
}

export function ensureDriveDateLocale(): void {
  const next = resolveDriveDateLocale()
  if (activeLocale === next) return
  dayjs.locale(next)
  activeLocale = next
}

export function parseDriveDate(iso: string): Dayjs | null {
  if (!iso?.trim()) return null
  const d = dayjs(iso)
  return d.isValid() ? d : null
}

/** Full local datetime for tooltip / aria-label. */
export function formatDriveListDateFull(iso: string): string {
  ensureDriveDateLocale()
  const d = parseDriveDate(iso)
  if (!d) return ""
  return d.format("dddd D MMMM YYYY [à] LT")
}

/** Short label for list column (relative when recent). */
function instantLabel(): string {
  return activeLocale === "en" ? "Just now" : "À l'instant"
}

function yesterdayLabel(): string {
  return activeLocale === "en" ? "Yesterday" : "Hier"
}

export function formatDriveListDateShort(iso: string, now: Dayjs = dayjs()): string {
  ensureDriveDateLocale()
  const d = parseDriveDate(iso)
  if (!d) return "—"

  if (d.isAfter(now)) {
    return d.format("LT")
  }

  const diffSec = now.diff(d, "second")
  if (diffSec < 50) return instantLabel()

  if (d.isSame(now, "day")) {
    if (diffSec < 6 * 3600) return d.fromNow()
    return d.format("LT")
  }

  if (d.isSame(now.subtract(1, "day"), "day")) {
    return yesterdayLabel()
  }

  if (now.diff(d, "day") < 7) {
    return d.fromNow()
  }

  if (d.isSame(now, "year")) {
    return d.format("D MMM")
  }

  return d.format("D MMM YYYY")
}

export function formatDriveListDate(iso: string): {
  short: string
  full: string
  dateTime?: string
} {
  const d = parseDriveDate(iso)
  if (!d) return { short: "—", full: "" }
  return {
    short: formatDriveListDateShort(iso),
    full: formatDriveListDateFull(iso),
    dateTime: d.toISOString(),
  }
}
