import React, { useState, useCallback } from 'react';
import { TouchableOpacity, View } from 'react-native';

import TextInput from '../TextInput';
import AndroidDatePickerDialog from './Dialog/AndroidDialog';
import useCalculateDate from './hooks/useCalculateDate';
import useFormatDate from './hooks/useFormatDate';
import type { DatePickerProps } from './types';

type DatePickerAndroidProps = Omit<
  DatePickerProps,
  'variant' | 'monthPickerConfirmLabel' | 'monthPickerCancelLabel'
> & {
  variant?: 'default' | 'month-year';
};
const DatePickerAndroid = ({
  value,
  minDate,
  maxDate,
  label,
  placeholder,
  onChange,
  displayFormat,
  disabled = false,
  required,
  error,
  helpText,
  style,
  testID,
  variant = 'default',
  renderSelectedValue,
  locale,
}: DatePickerAndroidProps) => {
  const [open, setOpen] = useState(false);

  const { displayValue, format } = useFormatDate({
    displayFormat,
    locale,
    value,
  });

  useCalculateDate({ minDate, maxDate, onChange, value });

  const onPress = useCallback(() => {
    setOpen(true);
  }, []);

  return (
    <TouchableOpacity
      onPress={onPress}
      disabled={disabled}
      testID="date-picker-android-touchable-opacity"
    >
      <View pointerEvents="none" testID="datePickerInputAndroid">
        <TextInput
          label={label}
          value={displayValue}
          suffix="calendar-dates-outlined"
          placeholder={placeholder || format}
          disabled={disabled}
          error={error}
          required={required}
          helpText={helpText}
          style={style}
          testID={testID}
          renderInputValue={
            renderSelectedValue !== undefined && !!value
              ? (inputProps) =>
                  renderSelectedValue(
                    {
                      date: value,
                      formattedDateString: displayValue,
                    },
                    inputProps
                  )
              : undefined
          }
        />
      </View>
      <AndroidDatePickerDialog
        open={open}
        onClose={() => setOpen(false)}
        value={value}
        minDate={minDate}
        maxDate={maxDate}
        onChange={onChange}
        variant={variant}
      />
    </TouchableOpacity>
  );
};

export default DatePickerAndroid;
