import { HStack, Input, InputGroup, InputLeftAddon, InputRightAddon } from 'native-base';
import React, { useState } from 'react';
import { KeyboardAvoidingView, Platform } from 'react-native';

type MinutesSetterProps = {
  minutes: number;
  onSubmit: (minutes: number) => void;
  minValue?: number;
  maxValue?: number;
  leftAddon?: string;
  rightAddon?: string;
};

const MinutesSetter = ({
  minutes,
  onSubmit,
  minValue = 0,
  maxValue = 90,
  leftAddon,
  rightAddon = 'minutes',
}: MinutesSetterProps) => {
  const [value, setValue] = useState(minutes.toString());
  const onChangeHandler = (value: string) => {
    const parsed = Number.parseInt(value);
    if (Number.isNaN(parsed)) {
      setValue(minValue.toString());
    } else if (parsed > maxValue) {
      setValue(maxValue.toString());
    } else {
      setValue(parsed.toString());
    }
  };

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={{ flex: 1 }}
      enabled
    >
      <HStack space={4} className="w-full items-center">
        <InputGroup>
          {leftAddon && <InputLeftAddon className="text-sm">{leftAddon}</InputLeftAddon>}
          <Input
            keyboardType="number-pad"
            w="50px"
            className="text-center"
            maxLength={2}
            defaultValue={value}
            returnKeyType="done"
            onChangeText={onChangeHandler}
            onSubmitEditing={() => onSubmit(+value)}
          />
          <InputRightAddon>{rightAddon}</InputRightAddon>
        </InputGroup>
      </HStack>
    </KeyboardAvoidingView>
  );
};

export default MinutesSetter;
