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

import { Input } from '../../Input';
import { Modal } from '../../Modal';
import { Button } from '../../Button';
import SpinnerTimePicker from '../SpinnerTimePicker';

import ClockIcon from 'assets/icons/travels-screens/clock-solid.svg';
import { Colors } from 'src/theme';

type Props = {
  selectedTime?: (date: Date) => void;
  formikError?: string | boolean;
  headerTitle?: string;
  defaultTime?: Date | null;
  placeholder?: string;
  inputHeader?: string;
};

export const InputTimePicker: FC<Props> = ({
  selectedTime,
  formikError,
  headerTitle,
  defaultTime,
  placeholder,
  inputHeader
}) => {
  const [visible, setVisible] = useState(false);
  const [spinnerSelectedTime, setSpinnerSelectedTime] = useState<Date | null>(defaultTime ?? null);

  const roundToNearest5Min = (date: Date) => {
    const ms = 1000 * 60 * 5;
    return new Date(Math.round(date.getTime() / ms) * ms);
  };

  const onButtonPress = () => {
    setVisible(false);
    if (selectedTime) {
      selectedTime(spinnerSelectedTime ?? new Date());
      if (!spinnerSelectedTime) {
        setSpinnerSelectedTime(roundToNearest5Min(new Date()));
      }
    }
  };

  return (
    <View style={{ flex: 1 }}>
      <Input
        icon={<ClockIcon fill={Colors.LIGHT_GRAY} width={20} height={20} />}
        header={inputHeader ?? 'Time'}
        value={
          defaultTime
            ? defaultTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            : ''
        }
        isFocused={(b) => setVisible(b)}
        onBlur={() => {}}
        inputMode={'none'}
        placeholder={placeholder ?? 'Choose a time'}
        formikError={formikError}
      />
      <Modal
        visibleInPercent={'50%'}
        onRequestClose={() => setVisible(false)}
        headerTitle={headerTitle ?? 'Select Time'}
        visible={visible}
      >
        <SpinnerTimePicker selectedTime={(date) => setSpinnerSelectedTime(date)} />
        <Button onPress={onButtonPress}>Done</Button>
      </Modal>
    </View>
  );
};
