import timezones from 'timezones-list';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';

dayjs.extend(utc);
dayjs.extend(timezone);

/**
 * Returns the offset from UTC in hours for the current locale.
 * @param {string} timeZone Timezone to get offset for
 * @returns {number} The offset from UTC in hours.
 *
 * Generated by Trelent
 */
export const getTimezoneOffset = (timeZone: string): number => {
  const now = new Date();
  const tzString = now.toLocaleString('en-US', {
    timeZone
  });
  const localString = now.toLocaleString('en-US');
  const diff = (Date.parse(localString) - Date.parse(tzString)) / 3600000;
  const offset = diff + now.getTimezoneOffset() / 60;
  return -offset;
};

/**
 * Returns a list of timezones sorted by their offset from UTC.
 * @returns {object[]} A list of the given timezones sorted by their offset from UTC.
 *
 * Generated by Trelent
 */
export const getTimeZoneList = () => {
  const result = timezones
    .map((timezone) => {
      try {
        let display = dayjs().tz(timezone.tzCode).format('Z');

        return {
          name: `(UTC${display}) ${timezone.tzCode}`,
          value: timezone.tzCode,
          time: getTimezoneOffset(timezone.tzCode)
        };
      } catch (e) {}
    })
    .filter((item) => item);

  result.sort((a, b) => {
    if (!a || !b) return 0;
    if (a.time > b.time) {
      return 1;
    }

    if (b.time > a.time) {
      return -1;
    }

    return 0;
  });

  return [
    {
      name: 'UTC',
      time: 0,
      value: 'UTC'
    },
    ...result
  ] as {
    name: string;
    value: string;
    time: number;
  }[];
};
export const timeZoneList = getTimeZoneList();

export const getTimezoneCodeFromStr = (timeString: string | Date) => {
  if (typeof timeString !== 'string' || !timeString.includes(':')) {
    return '+00:00';
  }

  if (timeString.includes('+')) {
    const timezoneMatch = timeString.split('+');
    return `+${timezoneMatch[1]}`;
  } else if (timeString.includes('-')) {
    const timezoneMatch = timeString.split('-');
    return `-${timezoneMatch[1]}`;
  } else {
    return '+00:00';
  }
};

export const getSystemTime = (timeZone: string) => {
  const timezoneDiff = getTimezoneOffset(timeZone);
  const now = Date.now();
  const targetTime = now + timezoneDiff * 60 * 60 * 1000;
  return dayjs(targetTime).format('YYYY-MM-DD HH:mm:ss dddd');
};
