import moment from "moment";
import * as momentTz from "moment-timezone";
import { useLocale } from "../hooks/useLocale";

export const getFormattedDateByTimeZone = (
  date: any = "",
  timeZone: string,
  dateFormat: string = "",
  fromNow: boolean = false,
  locale: string = "en"
) => {
  let momentDate: moment.Moment = moment();
  if (!date || !timeZone) return;

  if (Number.isInteger(date * 1)) {
    if (date.toString().length > 10) date = date / 1000;

    momentDate = momentTz.unix(date).tz(timeZone);
  } else if (typeof date === "string") {
    momentDate = momentTz.utc(date).tz(timeZone);
  }

  if (!momentDate) return;

  if (dateFormat)
    return `${moment(momentDate).format(dateFormat)} ${
      fromNow ? `(${momentDate.lang(locale).fromNow()})` : ""
    }`;

  if (momentTz.utc().tz(timeZone).isSame(momentDate, "day")) {
    return `${useLocale("date_today")} ${useLocale("at")} ${momentDate.format(
      "h:mm A"
    )}`;
  } else if (
    momentTz.utc().tz(timeZone).subtract(1, "d").format("DD") ===
    momentDate.format("DD")
  ) {
    return `${useLocale("date_yesterday")} ${useLocale(
      "at"
    )} ${momentDate.format("h:mm A")}`;
  }

  return `${momentDate.format("Y/m/d h:mm A")} ${
    fromNow ? `(${momentDate.lang(locale).fromNow()})` : ""
  }`;
};

export const GetFormatForMoment = (dateFormat: string) => {
  let format = "MM/DD/YYYY";
  if (dateFormat === "m/d/Y") {
    format = "MM/DD/YYYY";
  } else if (dateFormat === "d/m/Y") {
    format = "DD/MM/YYYY";
  } else if (dateFormat === "Y/m/d") {
    format = "YYYY/MM/DD";
  }

  return format;
};

export const getAbbvTimezone = (timezone: string) => {
  const abbr = moment.tz(timezone).zoneAbbr();
  return abbr;
};
