import React, {useCallback} from 'react';
import {Modal} from 'react-native';
import {useTranslation} from 'react-i18next';
import MonthPicker, {EventTypes} from 'react-native-month-year-picker';
import {isAndroid, isIos} from '@shared/utils';
import {SHARED_STRINGS} from '@shared/strings';

export interface YearMonthPickerProps {
  onClose: () => void;
  value?: Date;
  onChange?: (newDate?: Date) => void;
}

const TODAY = new Date();

// TODO: Design with HuGo components
export function YearMonthPicker({
  value,
  onChange,
  onClose,
}: YearMonthPickerProps) {
  const {t, i18n} = useTranslation();

  const onDateChange = useCallback(
    (event: EventTypes, newDate: Date) => {
      onClose();
      if (event === 'dateSetAction') {
        onChange?.(newDate);
      }
      if (event === 'dismissedAction') {
        onChange?.(undefined);
      }
    },
    [onChange, onClose],
  );

  const picker = (
    <MonthPicker
      onChange={onDateChange}
      value={value || TODAY}
      locale={i18n.language}
      okButton={t(SHARED_STRINGS.APPLY)}
      cancelButton={t(SHARED_STRINGS.CLEAR)}
      neutralButton={t(SHARED_STRINGS.CANCEL)}
      {...(isAndroid && {mode: 'short'})}
    />
  );

  return isIos ? (
    <Modal transparent onDismiss={onClose} onRequestClose={onClose}>
      {picker}
    </Modal>
  ) : (
    picker
  );
}
