import * as React from 'react';
import * as R from 'ramda';

import Icons from '../Icons';
import Input from '../Input';
import Modal from '../Modal';

import { Months } from './utils/months.enum';
import YEARS from './utils/year';
import { SelectYear, SelectYearWrapper, InputWrapper, ModalStyles } from './DatePicker.styled';
import IntroWithSeasons from './components/IntroWithSeasons';
import Calendar from './components/Calendar';

interface IProps {}

interface IState {
  year: number;
  month: number;
  day: number;
  dayOfTheWeek: number;
  active: boolean;
  input: string;
  inValid: boolean | string;
}

export default class extends React.PureComponent<IProps, IState> {
  state = {
    year: new Date().getFullYear(),
    month: new Date().getMonth(),
    day: new Date().getDate(),
    dayOfTheWeek: new Date().getDay(),
    active: false,
    input: '',
    inValid: false,
  }

  increaseYear = () => this.setState(prevState => ({ year: prevState.year + 1 }));
  decreaseYear = () => this.setState(prevState => ({ year: prevState.year - 1 }));

  setCorrectDateDigit = (digit: number): string|number => digit > 9 ? digit : `0${digit}`;

  dateValue = ({ currentTarget: { value } }: any) => parseInt(value.split('-')[0], 10)

  setValue = (e: React.ReactEventHandler<HTMLButtonElement>, i: number) => {
    const { year, month } = this.state;
    const day = this.dateValue(e);
    this.setState({
      day,
      dayOfTheWeek: i,
      input: `${this.setCorrectDateDigit(day)}/${this.setCorrectDateDigit(month + 1)}/${year}`,
    });
  }

  onClose = (active: boolean) => {
    this.setState({ active });
    if (this.state.input === '') {
      const { year, month, day } = this.state;
      this.setState({
        input: `${this.setCorrectDateDigit(day)}/${this.setCorrectDateDigit(month + 1)}/${year}`
      });
    }
  }

  onChangeMonth = (event: any) => this.setState({
    month: this.dateValue(event),
    input: `${this.setCorrectDateDigit(this.state.day)}/${this.setCorrectDateDigit(this.dateValue(event) + 1)}/${this.state.year}`,
  })

  onChangeYear = (event: any ) => this.setState({
    year: this.dateValue(event),
    input: `${this.setCorrectDateDigit(this.state.day)}/${this.setCorrectDateDigit(this.state.month + 1)}/${this.dateValue(event)}`,
  })

  onChangeInput = (value: string) => this.setState({
    day: parseInt(value.split('/')[0], 10),
    month: parseInt(value.split('/')[1], 10) - 1,
    year: parseInt(value.split('/')[2], 10),
    input: value
  });

  isInvalidDate = () => {
    const { input } = this.state;

    if (
      input.match(/(0[1-9]|[12][0-9]|3[01])[/](0[1-9]|1[012])[/](19|20)\d\d/) &&
      input.length === 10
    ) {
      this.setState({ inValid: false });
      return;
    }

    this.setState({ inValid: 'Insira uma data válida por favor' });

  }

  render () {
    const { year, month, day, dayOfTheWeek, active, inValid } = this.state;
  
    return (
      <React.Fragment>
        <InputWrapper>
          <Input
            type='text'
            placeholder='selecione uma data'
            value={this.state.input}
            onChange={(e) => this.onChangeInput(e.target.value)}
            isInvalid={inValid}
            onBlur={this.isInvalidDate}
          />
          <button  onClick={() => this.setState({ active: true })}>
            <Icons.Dashboard width={20} height={20} />
          </button>
        </InputWrapper>
        <ModalStyles>
          <div id='modal'></div>
          <Modal
            selector='#modal'
            active={active}
            onClose={this.onClose}
            onConfirmText='Selecionar'
            onConfirm={false}
            onConfirmType='link'
          >
            <IntroWithSeasons
              dayWeek={dayOfTheWeek}
              day={day}
              month={month}
              year={year}
            />

            <SelectYearWrapper>
              <SelectYear
                id='select-month'
                onChange={this.onChangeMonth}
                value={month}
              >
                {R.range(0, 12).map((mon: number) => (
                  <option value={mon} key={Math.random()}>{Months[mon]}</option>)
                )}
              </SelectYear>
              <label htmlFor='select-month'>
                <Icons.Arrow degree={180} width={15} height={15} />
              </label>
            </SelectYearWrapper>

            <SelectYearWrapper>
              <SelectYear
                id='select-year'
                onChange={this.onChangeYear}
                value={year}
              >
                {YEARS.map((mappedYear: any) => (
                  <option value={mappedYear} key={Math.random()}>{mappedYear}</option>
                ))}
              </SelectYear>
              <label htmlFor='select-year'>
                <Icons.Arrow degree={180} width={15} height={15} />
              </label>
            </SelectYearWrapper>

            <Calendar
              year={year}
              month={month}
              day={day}
              dayOfTheWeek={dayOfTheWeek}
              selectedDayWeek={(e) => this.setState({ dayOfTheWeek: e })}
              onClick={this.setValue}
            />
          </Modal>
        </ModalStyles>
      </React.Fragment>
    )
  }
}