import { de, enGB, sk } from "date-fns/locale"
import { $store } from "@racletteCore"
import {
  format as formatFns,
  isValid,
  parseISO,
  formatDistance as formatDistanceFns,
  formatDistanceToNow as formatDistanceToNowFns,
  intervalToDuration,
  differenceInDays,
  differenceInMinutes,
} from "date-fns"
const locales = {
  de,
  en: enGB,
  enGB,
  sk,
}

locales["de-DE"] = de
locales["de-AT"] = de
locales["en-UK"] = enGB
locales["en-US"] = enGB
const parseDate = (input) => {
  if (typeof input === "string") {
    let encodedInput = input

    if (encodedInput.includes("&#x2F;")) {
      // fix encoding coming from mustache.js
      encodedInput = encodedInput.replace(/&#x2F;/g, "/")
    }

    // Handle JSON date representation
    const match = /\/Date\((\d+)([-+]\d+)?\)\//.exec(encodedInput)

    if (match) {
      return new Date(parseInt(match[1], 10))
    }

    // Handle standard date string formats (e.g., ISO 8601)
    const parsedDate = new Date(input)

    if (!isNaN(parsedDate.getTime())) {
      return parsedDate
    }
  } else if (input instanceof Date) {
    return input
  }

  // If input is not a valid date, return null
  return null
}

// TODO: expand the functions below with the date-validator & parser like in formatDistanceToNow, to support rendering tempalte syntaxt (see ExternalApiCard.vue)
// TODO: replace the locale handling
const format = (date, formatStr = "PP") =>
  formatFns(date, formatStr, {
    locale: locales[$store.getState(["ui", "locale"])], // or global.__localeId__
  })

const formatISO = (dateAsISOString, formatStr = "PP") =>
  formatFns(parseISO(dateAsISOString), formatStr, {
    locale: locales[$store.getState(["ui", "locale"])], // or global.__localeId__
  })
const formatDistance = (date: Date, baseDate: Date) =>
  formatDistanceFns(date, baseDate, {
    locale: locales[$store.getState(["ui", "locale"])], // or global.__localeId__
  })

const formatDistanceToNow = (dateInput: Date) => {
  if (!dateInput) {
    return ""
  }
  const date = parseDate(dateInput)

  if (!date) {
    throw new Error("Invalid date input")
  }

  return formatDistanceToNowFns(date, {
    locale: locales[$store.getState(["ui", "locale"])], // or global.__localeId__
  })
}

const isTimestamp = (input) => {
  if (typeof input !== "string") {
    return false
  }

  // Regular expression to match common timestamp formats
  const timestampRegex =
    /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?$/

  if (!timestampRegex.test(input)) {
    return false
  }

  const parsedAsDate = new Date(input)

  return isValid(parsedAsDate)
}

export {
  format,
  isValid,
  formatISO,
  isTimestamp,
  formatDistance,
  intervalToDuration,
  differenceInDays,
  differenceInMinutes,
  formatDistanceToNow,
}
