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

import TextInput from '../TextInput';
import type { TimePickerProps } from './types';

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

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

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

  return (
    <TouchableOpacity
      onPress={onPress}
      disabled={disabled}
      testID="time-picker-android-touchable-opacity"
    >
      <View pointerEvents="none" testID="timePickerInputAndroid">
        <TextInput
          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}
    </TouchableOpacity>
  );
};

export default TimePickerAndroid;
