import React, { useState, useEffect, useRef } from 'react';
import classNames from 'classnames/bind';
import ModuleButton from 'components/items/ModuleButton';
import moment from 'moment';
import { clone } from 'store/utils/helper';
import styleIdentifiers from './schedule.scss';

const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {
  num: number;
}

export interface DispatchProps {}

export interface OwnProps {
  initialValue?: {};
}

export type ScheduleProps = StateProps & DispatchProps & OwnProps;

const Schedule = (props: ScheduleProps): JSX => {
  // Initial value
  const { noMargin, label, name, input, initialValue, keyFrom, keyTo } = props;

  const init = input.value || initialValue || [[], [], [], [], [], [], []];

  const isArray = Array.isArray(init);

  const [days, setDays] = useState(init);
  const daysKeys = Object.keys(days);

  const fromInput = useRef(null);
  const toInput = useRef(null);

  useEffect(() => {
    // save it to redux form when component update
    if (input) input.onChange(days);
  }, [days]); // give value on which the effect depend

  const saveDays = () => {
    // Use a copy (or same object)
    const newDays = clone(days);
    setDays(newDays);
    input.onChange(newDays);
  };

  const multipleAdd = (first, last): void => {
    const from = fromInput && fromInput.current && fromInput.current.value;
    const to = toInput && toInput.current && toInput.current.value;
    if (!from || !to) return;

    for (let i = first; i < last; i++) {
      days[daysKeys[i]].push([from, to]);
    }

    saveDays();
  };

  const addWeek = (): void => {
    multipleAdd(0, 5);
  };

  const addWeekend = (): void => {
    multipleAdd(5, 7);
  };

  const addAll = (): void => {
    multipleAdd(0, 7);
  };

  const addTimeSlot = day => {
    const last = day[day.length - 1];

    if (last && last[1]) {
      const to = last[1];
      const toTime = moment(to, 'HH:mm');
      const newFrom = moment(toTime)
        .hours(toTime.hours() + 1)
        .format('HH:mm');
      const newTo = moment(toTime)
        .hours(toTime.hours() + 2)
        .format('HH:mm');
      day.push([newFrom, newTo]);
    } else {
      day.push(['08:00', '18:00']);
    }

    saveDays();
  };

  const removeTimeSlot = (day, index: string | number): void => {
    // item is a element of days
    day.splice(index, 1);
    saveDays();
  };

  const handleChange = (event, timeSlot, index): void => {
    timeSlot[index] = event.target.value;
    saveDays();
  };

  const renderTimeSlot = (timeSlot, day, index) => (
    <div className={styles('hours')} key={index}>
      <input
        placeholder="from"
        type="time"
        value={timeSlot[keyFrom || 0]}
        onChange={(event): void => handleChange(event, timeSlot, 0)}
      />
      <input
        placeholder="to"
        type="time"
        value={timeSlot[keyTo || 1]}
        onChange={(event): void => handleChange(event, timeSlot, 1)}
      />
      <div className={styles('remove')} onClick={(): void => removeTimeSlot(day, index)}>
        x
      </div>
    </div>
  );

  return (
    <div className={styles('Schedule', noMargin && 'no-margin')}>
      <div className={styles('label')}>{label || name}</div>
      <div className={styles('quick-add')}>
        <div className={styles('title')}>Quick add</div>
        <div className={styles('hours')}>
          <input ref={fromInput} placeholder="from" type="time" />
          <input ref={toInput} placeholder="to" type="time" />
          <ModuleButton noMargin small relative label="+ week" action={addWeek} />
          <ModuleButton noMargin small relative label="+ weekend" action={addWeekend} />
          <ModuleButton noMargin small relative label="+ all" action={addAll} />
        </div>
      </div>
      <div className={styles('days-wrapper')}>
        {daysKeys.map((key, dayIndex) => (
          <div className={styles('day-wrapper')} key={dayIndex}>
            <div className={styles('left')}>
              <div className={styles('day')}>{DAYS[dayIndex]}</div>
              {days[key].map((timeSlot, index) => renderTimeSlot(timeSlot, days[key], index))}
            </div>
            <ModuleButton
              noMargin
              small
              relative
              label="+ slot"
              action={(): void => addTimeSlot(days[key])}
            />
          </div>
        ))}
      </div>
    </div>
  );
};

export default Schedule;
