import React, { FC, useEffect, useState } from 'react';
import { Platform, View } from 'react-native';
import DateTimePicker, { DateTimePickerEvent } from '@react-native-community/datetimepicker';
import { Picker } from 'react-native-wheel-pick';
import { Colors } from '../../theme';

type Props = {
  selectedTime: (date: Date) => void;
};

const SpinnerTimePicker: FC<Props> = ({ selectedTime }) => {
  const now = new Date();
  const [value, setValue] = useState<Date>(new Date());
  const [selectedHour, setSelectedHour] = useState(now.getHours().toString().padStart(2, '0'));
  const [selectedMinute, setSelectedMinute] = useState(
    (Math.round(now.getMinutes() / 5) * 5).toString().padStart(2, '0')
  );

  const hours = Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0'));
  const minutes = Array.from({ length: 12 }, (_, i) => (i * 5).toString().padStart(2, '0'));

  useEffect(() => {
    const updated = new Date();
    updated.setHours(Number(selectedHour));
    updated.setMinutes(Number(selectedMinute));
    updated.setSeconds(0);
    updated.setMilliseconds(0);
    setValue(updated);
    selectedTime(updated);
  }, [selectedHour, selectedMinute]);

  const onChange = (event: DateTimePickerEvent, selectedSpinnerTime?: Date) => {
    if (event.type === 'set' && selectedSpinnerTime) {
      setValue(selectedSpinnerTime);
      selectedTime(selectedSpinnerTime);
    }
  };

  if (Platform.OS === 'ios') {
    return (
      <DateTimePicker
        value={value}
        mode="time"
        display="spinner"
        textColor={Colors.DARK_BLUE}
        onChange={onChange}
        minuteInterval={5}
      />
    );
  }

  return (
    <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
      <Picker
        style={{ marginVertical: 16, backgroundColor: 'white', width: '50%', height: 215 }}
        selectedValue={selectedHour}
        pickerData={hours}
        onValueChange={(value: React.SetStateAction<string>) => setSelectedHour(value)}
      />
      <Picker
        style={{ marginVertical: 16, backgroundColor: 'white', width: '50%', height: 215 }}
        selectedValue={selectedMinute}
        pickerData={minutes}
        onValueChange={(value: React.SetStateAction<string>) => setSelectedMinute(value)}
      />
    </View>
  );
};

export default SpinnerTimePicker;
