import React, { useState, useEffect } from 'react';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

// Import actions here

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import moment, { Moment } from 'moment';
import CustomSelect from 'components/formItems/CustomSelect/CustomSelect';
import styleIdentifiers from './TimePicker.module.scss';

const styles = classNames.bind(styleIdentifiers);

export interface TimePickerProps {
  itemClassName?: string;
  className?: string;
  step?: number;
  // default distance from min or max (usually not use together)
  diff?: number;
  // min hour
  min?: string | Moment;
  // max hour
  min?: string | Moment;
}

const HOUR_FORMAT = 'HH:mm';
const TimePicker = (props: TimePickerProps) => {
  const { itemClassName, large = false, className, step = 30, diff = 0, min, max } = props;

  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const minHour = moment(min || '00:00', HOUR_FORMAT);
  const maxHour = moment(max || '23:59', HOUR_FORMAT);

  // if only min OR max, force diff of step between the two
  // if min and max, a diff can still be provided
  const diffTime = (min && !max) || (!min && max) ? diff || step : diff;

  const listHours = [];
  let check;
  const current = moment(minHour);

  if (min && diffTime) current.add(diffTime, 'minutes');
  if (max && diffTime) maxHour.subtract(diffTime, 'minutes');
  do {
    listHours.push(current.format(HOUR_FORMAT));
    current.add(step, 'minutes');
    check = current.isSameOrBefore(maxHour);
  } while (check);

  return (
    <CustomSelect
      {...props}
      className={styles('time-picker', className)}
      itemClassName={styles('item', itemClassName)}
      relativeSuggestion={!large}
      noCheck
      items={listHours}
    />
  );
};

export default TimePicker;
