import DateTimePicker from '@react-native-community/datetimepicker';
import React, { useState, useCallback } from 'react';
import { View } from 'react-native';
import formatTime from 'date-fns/fp/format';

import TextInput from '../TextInput';
import { StyledTouchableOpacity } from './StyledTimePicker';
import type { InternalTimePickerProps } from './types';

const TimePickerAndroid = ({
  value,
  label,
  placeholder,
  onChange,
  displayFormat = 'hh:mm aa',
  disabled = false,
  required,
  error,
  helpText,
  style,
  testID,
  showSuffix = true,
  TextInputComponent,
  inputProps,
  groupStyleEnabled = false,
}: InternalTimePickerProps) => {
  const [open, setOpen] = useState(false);

  const is12Hour = displayFormat.includes('hh');
  const displayValue = value ? formatTime(displayFormat, value) : '';
  const pickerInitValue = value || new Date();

  const InputComponent = TextInputComponent || TextInput;

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

  return (
    <StyledTouchableOpacity
      onPress={onPress}
      disabled={disabled}
      themeGroupStyleEnabled={groupStyleEnabled}
      themeHasError={!!error}
      testID="time-picker-android-touchable-opacity"
    >
      <View pointerEvents="none" testID="timePickerInputAndroid">
        <InputComponent
          {...inputProps}
          label={label}
          value={displayValue}
          suffix={showSuffix ? 'clock-3' : undefined}
          placeholder={placeholder || displayFormat}
          disabled={disabled}
          error={error}
          required={required}
          helpText={helpText}
          style={style}
          testID={testID}
        />
      </View>
      {open ? (
        <DateTimePicker
          testID="timePickerAndroid"
          mode="time"
          value={pickerInitValue}
          display="default"
          onChange={(_: any, date: Date | undefined) => {
            setOpen(false);
            if (date) {
              onChange(date);
            }
          }}
          is24Hour={!is12Hour}
        />
      ) : null}
    </StyledTouchableOpacity>
  );
};

export default TimePickerAndroid;
