import moment from 'moment';
import React from 'react';
import type { ViewStyle } from 'react-native';
import { requireNativeComponent, UIManager, Platform } from 'react-native';
import { NATIVE_FORMAT } from './constants';

const LINKING_ERROR =
  `The package 'react-native-month-year-picker' doesn't seem to be linked. Make sure: \n\n${Platform.select(
    { ios: "- You have run 'pod install'\n", default: '' }
  )}- You rebuilt the app after installing the package\n` +
  `- You are not using Expo Go\n`;

type NativeMonthYearPickerViewProps = {
  style?: ViewStyle;
  textColor?: string;
  value: number;
  onChange: (event: { nativeEvent: { newDate: string } }) => void;
  minimumDate?: number;
  maximumDate?: number;
  autoTheme?: boolean;
  locale?: string;
};

const ComponentName = 'MonthYearPickerView';

const NativeMonthYearPickerView =
  UIManager.getViewManagerConfig(ComponentName) != null
    ? requireNativeComponent<NativeMonthYearPickerViewProps>(ComponentName)
    : () => {
        throw new Error(LINKING_ERROR);
      };

type MonthYearPickerProps = {
  style?: ViewStyle;
  value?: Date;
  onChange: (date: Date) => void;
  minimumDate?: Date;
  maximumDate?: Date;
  autoTheme?: boolean;
  locale?: string;
  textColor?: string;
};
const MonthYearPickerView = ({
  value = new Date(),
  minimumDate,
  maximumDate,
  onChange,
  locale = 'en',
  textColor,
  ...props
}: MonthYearPickerProps) => {
  return (
    <NativeMonthYearPickerView
      textColor={textColor}
      value={value.getTime()}
      minimumDate={minimumDate ? minimumDate.getTime() : undefined}
      maximumDate={maximumDate ? maximumDate.getTime() : undefined}
      onChange={(event) => {
        const { nativeEvent } = event;
        const date = moment(nativeEvent.newDate, NATIVE_FORMAT).toDate();
        onChange(date);
      }}
      locale={locale}
      {...props}
    />
  );
};

export default MonthYearPickerView;
