import React from 'react';
import cx from 'classnames';
import { Select } from '../select';
import { t } from './i18n';
import { getTimezoneOptions, normalizeTimezone } from './utils';
import type { TimezoneOption } from './types';
import type { SelectProps } from '../select';

const CLASSNAME = 'TimezoneSelector';

export interface TimezoneSelectorProps<T extends TimezoneOption = TimezoneOption>
    extends SelectProps<T> {
    /**
     * Optional date to calculate timezone offsets for. If not provided, uses the current date.
     */
    date?: Date;
}

/**
 * TimezoneSelector provides a list of timezones and allows user to select a single one from the list.
 *
 * @type molecule
 * @status live
 * @tags form-elements, selects
 *
 */
export function TimezoneSelector({
    placeholder = t('timezone'),
    filterPlaceholder = t('searchTimezone'),
    className,
    testId = CLASSNAME,
    initialValue,
    selectedValue,
    date,
    options,
    quickSelections,
    recentSelections,
    ...props
}: TimezoneSelectorProps) {
    const initialTimezone = normalizeTimezone(initialValue);
    const selectedTimezone = normalizeTimezone(selectedValue);

    const timezonesOptions = React.useMemo(() => {
        if (options) {
            return options;
        }
        return getTimezoneOptions(false, date);
    }, [options, date]);

    return (
        <Select
            {...props}
            placeholder={placeholder}
            initialValue={initialTimezone}
            selectedValue={selectedTimezone}
            recentSelections={recentSelections}
            quickSelections={quickSelections}
            filterPlaceholder={filterPlaceholder}
            className={cx(CLASSNAME, className)}
            testId={testId}
            options={timezonesOptions}
        />
    );
}
