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

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

type DatePickerAndroidProps = Omit<
  InternalDatePickerProps,
  '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,
  TextInputComponent,
  inputProps,
  groupStyleEnabled = false,
}: DatePickerAndroidProps) => {
  const [open, setOpen] = useState(false);

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

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

  const InputComponent = TextInputComponent || TextInput;

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

  return (
    <StyledTouchableOpacity
      onPress={onPress}
      disabled={disabled}
      themeGroupStyleEnabled={groupStyleEnabled}
      themeHasError={!!error}
      testID="date-picker-android-touchable-opacity"
    >
      <View pointerEvents="none" testID="datePickerInputAndroid">
        <InputComponent
          {...inputProps}
          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
              ? (props) =>
                  renderSelectedValue(
                    {
                      date: value,
                      formattedDateString: displayValue,
                    },
                    props
                  )
              : undefined
          }
        />
      </View>
      <AndroidDatePickerDialog
        open={open}
        onClose={() => setOpen(false)}
        value={value}
        minDate={minDate}
        maxDate={maxDate}
        onChange={onChange}
        variant={variant}
      />
    </StyledTouchableOpacity>
  );
};

export default DatePickerAndroid;
