import dayjs from 'dayjs';
import localizedFormat from 'dayjs/plugin/localizedFormat';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import React from 'react';
import type { FC } from 'react';
import type { Timezone } from 'src/types';

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

/**
 * Converts a Date object (including time) to a specified timezone, and returns
 * a string representation of it in the browser's localized timezone.
 *
 * @param date Date object (including time)
 * @param iana IANA timezone string to use for conversion
 * @returns a string representing the date/time representation localized to
 * the provided timezone.
 */
export const format = ({
    date,
    iana,
    placeholder = '-- --',
}: {
    date?: Date;
    iana?: string;
    placeholder?: string;
}) =>
    !date || !iana
        ? placeholder
        : dayjs.utc(date).tz(iana).format('D MMM YYYY hh:mma');

/**
 * Converts a number to a string, appending '+' if the number is positive.
 *
 * @param n number to convert to "signed" string
 * @returns +/- prefixed string representing number
 */
export const signed = (n: number) => `${n > 0 ? '+' : ''}${n.toString()}`;

export interface TimezonedDatetimeProps {
    date: Date;
    timezone: Timezone;
}

const TimezonedDatetime: FC<TimezonedDatetimeProps> = ({
    date,
    timezone: { offset, abbreviation, iana },
}) => (
    <div className="TimezonedDatetime">
        <div className="TimezonedDatetime-timezone">
            {`${abbreviation} (UTC ${signed(offset)}):`}
        </div>
        <div className="TimezonedDatetime-formatted">
            {format({ date, iana })}
        </div>
    </div>
);

export default TimezonedDatetime;
