import React, { FunctionComponent, useEffect, useState } from 'react';
import { AtomSelect } from 'react/atoms/Select';
import moment from 'moment';
import { InputDateContainer, SelectorContainer} from './styles';
import { CSSObject } from "styled-components";

export interface IInputDateProps {
  date?: string;
  minYear?: string;
  maxYear?: string;
  width?: string;
  disabled?: boolean;
  required?: boolean;
  readOnly?: boolean;
  styles?: CSSObject;
  onChange?: (value: any) => void;
}

const createListDay = (year: string, month: string, date: string) => {
  const _year = !isNaN(Number(year)) ? year : moment(date).format('YYYY');
  const _month = !isNaN(Number(month)) ? month : date? moment(date).format('MM') : '01';
  const days = moment(`${_year}-${_month}`, 'YYYY-MM').daysInMonth();

  let list: { label: string; value: string; key: number }[] = [];
  for (let index = 1; index <= days; index++) {
    list.push({
      label: index < 10 ? `0${index}` : index.toString(),
      value: index < 10 ? `0${index}` : index.toString(),
      key: index,
    });
  }
  return list;
};

const createListYear = (minYear: string, maxYear: string) => {
  let list: { label: string; value: string; key: number }[] = [];
  for (let index = (parseInt(minYear)); index <= parseInt(maxYear); index++) {
    list.push({
      label: index.toString(),
      value: index.toString(),
      key: index,
    });
  }
  return list;
};

const createListMonth = () => {
  let list: { label: string; value: string; key: number }[] = [];
  for (let index = 1; index <= 12; index++) {
    list.push({
      label: index < 10 ? `0${index}` : index.toString(),
      value: index < 10 ? `0${index}` : index.toString(),
      key: index,
    });
  }
  return list;
};

export const AtomInputDate: FunctionComponent<IInputDateProps> = ({
  date = '',
  width,
  required = false,
  readOnly = false,
  disabled = false,
  styles,
  minYear = moment().subtract(100, 'y').format('YYYY'),
  maxYear = moment().add(100, 'y').format('YYYY'),
  onChange = () => { },
}: IInputDateProps) => {
  const [year, setYear] = useState<string>('YYYY');
  const [month, setMonth] = useState<string>('MM');
  const [day, setDay] = useState<string>('DD');
  const [newDate, setNewDate] = useState<string>(date)

  const monthList = createListMonth();
  const dayList = createListDay(year, month, date);
  const yearList = createListYear(minYear, maxYear);
  const labelDayList = dayList.map((day) => day.label);
  const labelMonthList = monthList.map((month) => month.label);
  const labelYearList = yearList.map((year) => year.label).reverse();

  useEffect(() => {
    if (!isNaN(Number(year)) && !isNaN(Number(month)) && !isNaN(Number(day))) {
      const newDate = moment(`${year}${month}${day}`, 'YYYYMMDD').format('MM-DD-YYYY');
      setNewDate(newDate);
      onChange(newDate);
    }
  }, [year, month, day]);

  useEffect(() => {
    let currDate = moment(date, 'MM-DD-YYYY');
    let month = currDate.format('MM');
    let day = currDate.format('DD');
    let year = currDate.format('YYYY');

    if (
      labelMonthList.includes(month.toString()) &&
      labelYearList.includes(year.toString()) &&
      labelDayList.includes(day.toString())
    ) {
      setMonth(month);
      setYear(year);
      setDay(day);
    }
  }, [date]);
  
  
  return (
    <InputDateContainer width={width}>
      <SelectorContainer
        data-testId="select-month"
      >
        <AtomSelect
          width='100%'
          items={labelMonthList}
          value={month}
          onChangeValue={(month: string) => setMonth(month)}
          disabled={disabled}
          required={required}
          readOnly={readOnly}
          styles={styles}
        />
      </SelectorContainer>
      <SelectorContainer
        data-testId="select-day"
      >
        <AtomSelect
          width='100%'
          items={labelDayList}
          value={day}
          onChangeValue={(day: string) => setDay(day)}
          disabled={disabled}
          required={required}
          readOnly={readOnly}
          styles={styles}
        />
      </SelectorContainer>
      <SelectorContainer
        data-testId="select-year"
      >
        <AtomSelect
          width='100%'
          items={labelYearList}
          value={year}
          onChangeValue={(year: string) => setYear(year)}
          disabled={disabled}
          required={required}
          readOnly={readOnly}
          styles={styles}
        />
      </SelectorContainer>
    </InputDateContainer>
  );
};
