import moment from 'moment';
import { useEffect, useState } from 'react';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useSettlementsCalendarMutation } from '../api/use-settlements-calendar-mutation';
import { CalendarAmountRow } from './calandar-amount-row';
import { CalendarSettlementItem } from './calendar-settlement-item'; 
import { CalendarGrid } from './calendar-grid';
import { 
  SettlementDays,
  SettlementsCalendarParams,
  SettlementsCalendarResponse,
  SettlementStatus
} from '../model/types';

export const CalendarWrap = () => {
  moment.locale('ko');

  const [mid, setMid] = useState<string>('nictest001m');
  const [yearMonth, setYearMonth] = useState<string>(moment().format('YYYY-MM'));
  const [totalCompletedAmount, setTotalCompletedAmount] = useState<number>(0);
  const [totalScheduledAmount, setTotalScheduledAmount] = useState<number>(0);
  const [scheduledList, setScheduledList] = useState<Array<SettlementDays | undefined>>([]);
  const [completedList, setCompletedList] = useState<Array<SettlementDays | undefined>>([]);
  const [scheduledDateList, setScheduledDateList] = useState<Array<number>>([]);
  const [completedDateList, setCompletedDateList] = useState<Array<number>>([]);
  
  const [lastMonth, setLastMonth] = useState<boolean>(false);

  const { mutateAsync: settlementsCalendar } = useSettlementsCalendarMutation();

  const callCalendar = () => {
    let params: SettlementsCalendarParams = {
      mid: mid,
      yearMonth: yearMonth
    };
    settlementsCalendar(params).then((rs: SettlementsCalendarResponse) => {
      setTotalCompletedAmount(rs.totalCompletedAmount);
      setTotalScheduledAmount(rs.totalScheduledAmount);
      setYearMonth(rs.yearMonth);
      let scheduleArr = [];
      let scheduleDateArr = [];
      let completedArr = [];
      let completedDateArr = [];
      if(!!rs.settlementDays && rs.settlementDays.length > 0){
        for(let i=0;i<rs.settlementDays.length;i++){
          let date = moment(rs.settlementDays[i]?.settlementDate).date();
          if(rs.settlementDays[i]?.settlementStatus === SettlementStatus.SCHEDULED){
            scheduleArr.push(rs.settlementDays[i]);
            scheduleDateArr.push(date);
          }
          else if(rs.settlementDays[i]?.settlementStatus === SettlementStatus.COMPLETED){
            completedArr.push(rs.settlementDays[i]);
            completedDateArr.push(date);
          }
        }
        setScheduledList(scheduleArr);
        setScheduledDateList(scheduleDateArr);
        setCompletedList(completedArr);
        setCompletedDateList(completedDateArr);
      }
    }).finally(() => {
      let maxYearMonth = moment().format('YYYY-MM');
      let maxYearMonthValue = moment(maxYearMonth).format('YYYYMM');
      let newYearMonth = moment(yearMonth).add(1, 'month').format('YYYY-MM');
      let newYearMonthValue = moment(newYearMonth).format('YYYYMM');
      if(parseInt(newYearMonthValue) <= parseInt(maxYearMonthValue)){
        setLastMonth(false);
      }
      else{
        setLastMonth(true);
      }
    });
  };

  const onClickToMoveMonthPrev = () => {
    let newYearMonth = moment(yearMonth).subtract(1, 'month').format('YYYY-MM');
    setYearMonth(newYearMonth);
  };
  const onClickToMoveMonthNext = () => {
    let maxYearMonth = moment().format('YYYY-MM');
    let maxYearMonthValue = moment(maxYearMonth).format('YYYYMM');
    let newYearMonth = moment(yearMonth).add(1, 'month').format('YYYY-MM');
    let newYearMonthValue = moment(newYearMonth).format('YYYYMM');
    if(parseInt(newYearMonthValue) <= parseInt(maxYearMonthValue)){
      setYearMonth(newYearMonth);
    }
  };
  
  useEffect(() => {
    callCalendar();
  }, [yearMonth]);
  return (
    <>
      <div className="calendar-wrap pt-30">
        <div className="input-wrapper top-select">
          <select>
            <option value="1">nicetest00g</option>
            <option value="2">nicetest00g</option>
            <option value="3">nicetest00g</option>
          </select>
        </div>
        
        <div className="month-group">
          <button 
            className="month-btn" 
            aria-label="이전 달"
            onClick={ onClickToMoveMonthPrev }
          >
            <img 
              src={ IMAGE_ROOT + '/ico_date_prev.svg' }
              alt="이전"
            />
          </button>
          <div className="month-title">{ moment(yearMonth).format('YYYY년 MM월') }</div>
          <button 
            className={ `month-btn ${lastMonth? 'disabled': ''}` }
            aria-label="다음 달"
            onClick={ onClickToMoveMonthNext }
          >
            <img 
              src={ IMAGE_ROOT + '/ico_date_next.svg' }
              alt="다음"
            />
          </button>
        </div>

        <div className="amount-group">
          <CalendarAmountRow
            amount={ totalCompletedAmount }
            settlementStatus={ SettlementStatus.COMPLETED }
          ></CalendarAmountRow>
          <CalendarAmountRow
            amount={ totalScheduledAmount }
            settlementStatus={ SettlementStatus.SCHEDULED }
          ></CalendarAmountRow>
        </div>

        <div className="legend-group">
          <div className="legend-item">
            <div className="legend-dot complete"></div>
            <div className="legend-text">정산 완료</div>
          </div>
          <div className="legend-item">
            <div className="legend-dot scheduled"></div>
            <div className="legend-text">입금 예정</div>
          </div>
        </div>

        <CalendarGrid
          yearMonth={ yearMonth }
          scheduledDateList={ scheduledDateList }
          completedDateList={ completedDateList }
        ></CalendarGrid>

        <div className="settlement-list">
        { (!!scheduledList && scheduledList.length > 0) &&
          <CalendarSettlementItem
            list={ scheduledList }
            settlementStatus={ SettlementStatus.SCHEDULED }
          ></CalendarSettlementItem>
        }
        { (!!completedList && completedList.length > 0) &&
          <CalendarSettlementItem
            list={ completedList }
            settlementStatus={ SettlementStatus.COMPLETED }
          ></CalendarSettlementItem>
        }
        </div>
      </div>
    </>
  );
};