import { Dropdown } from '@theorchard/suite-components';
import React, { useEffect } from 'react';
import OptionalTooltip from '../optionalTooltip';
import type { FC } from 'react';

// "HH:MM"
const formatRegex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;

export interface TimeOffsetPickerProps {
    /**
     * `options` must conform to formatRegex, will throw otherwise.
     */
    options: string[];
    onChange: (value: string) => void;
    /**
     * Function that formats a number of hours to string.
     */
    formatHours: (hours: number) => string;
    /**
     * Function that formats as number of minutes to string.
     */
    formatMinutes: (minutes: number) => string;
    /**
     * Current value. Must conform to formatRegex, will throw otherwise.
     */
    value: string;
    /**
     * Is it enabled?
     */
    enabled: boolean;
    /**
     * What's the tooltip say when it's disabled?
     */
    disabledMessage: string;
}

/**
 * Provides a mechanism for selecting a time period offset, in HH:MM format.
 */
const TimeOffsetPicker: FC<TimeOffsetPickerProps> = ({
    options,
    onChange,
    formatHours,
    formatMinutes,
    value,
    enabled,
    disabledMessage,
}) => {
    // could memoize this function
    const format = (option: string) => {
        const [hours, minutes] = option
            .split(':')
            // fun fact: if you just map(parseInt) you're going to have a bad time.
            .map(value => parseInt(value, 10));
        if (hours > 0) return formatHours(hours);
        return formatMinutes(minutes);
    };

    const toDropdownValue = (option: string) => ({
        label: format(option),
        value: option,
    });

    useEffect(() => {
        [...options, value].forEach(option => {
            if (!formatRegex.test(option))
                throw new Error(`Option does not match ${format}`);
        });
    }, [options, value]);

    return (
        <OptionalTooltip
            id="datepicker"
            className="TimeOffsetPicker"
            message={disabledMessage}
            enabled={!enabled}
        >
            <Dropdown
                options={options.map(toDropdownValue)}
                onChange={option => {
                    if (enabled && option) onChange(option.value);
                }}
                isDisabled={!enabled}
                value={toDropdownValue(value)}
            />
        </OptionalTooltip>
    );
};

export default TimeOffsetPicker;
