import type { Dayjs } from "dayjs";
import dayjs from "dayjs";
import LocalizedFormat from "dayjs/plugin/localizedFormat";
import i18next from "i18next";

export const formatDueDate = (start: string, end?: string | null) => {
  dayjs.extend(LocalizedFormat);
  const startDayjs = dayjs(start);
  const startDateString = getDateString(startDayjs);

  let endDayjs;
  let endDateString;
  if (end) {
    endDayjs = dayjs(end);
    endDateString = getDateString(endDayjs);
  }

  // at least `start` must be provided and valid
  if (!startDayjs.isValid()) {
    return i18next.t("Termin nicht festgelegt");
  }

  // when only `start` is provided, show only the start date with time
  if (!endDayjs || !endDayjs.isValid()) {
    return `${startDateString} ${getTimeString(startDayjs)} ${startDayjs.format(
      "[Uhr]"
    )}`;
  }

  // if startDayjs and endDayjs are on the same day, dont show the day twice
  if (startDateString === endDateString) {
    return `${startDateString} ${getTimeString(startDayjs)} - ${getTimeString(
      endDayjs
    )} ${endDayjs.format("[Uhr]")}`;
  }

  return `${startDateString} ${getTimeString(
    startDayjs
  )} - ${endDateString} ${getTimeString(endDayjs)}`;
};

export const getTimeString = (date?: Dayjs) => {
  if (date) {
    return `${date.format("HH:mm")}`;
  }
  return "";
};

export const getDateString = (date?: Dayjs) => {
  if (date) {
    return `${date.format("D. MMMM YYYY")}`;
  }
  return "";
};

export const getWeekday = (date: Dayjs) => {
  if (date) {
    return `${date.format("dd")}`;
  }
  return "";
};
