import moment from 'moment';
import { ChangeEvent, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useSettlementsCalendarMutation } from '../api/use-settlements-calendar-mutation';
import { CalendarAmountRow } from './calendar-amount-row';
import { CalendarSettlementItem } from './calendar-settlement-item';
import { CalendarGrid } from './calendar-grid';
import {
  SettlementDays,
  SettlementsCalendarParams,
  SettlementsCalendarResponse,
  SettlementStatus
} from '../model/types';
import { useStore } from '@/shared/model/store';
import { showAlert } from '@/widgets/show-alert';
import { snackBar } from '@/shared/lib';

export const CalendarWrap = () => {
  const { t, i18n } = useTranslation();
  moment.locale(i18n.language);
  const midOptions = useStore.getState().UserStore.selectOptionsMids;
  const userMid = useStore.getState().UserStore.mid;
  let midItem = midOptions.filter((value, index) => {
    return value.value === userMid;
  });

  const [mid, setMid] = useState<string>((midItem.length > 0)? userMid: '');
  const [yearMonth, setYearMonth] = useState<string>(moment().format('YYYYMM'));
  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 [filterDate, setFilterDate] = useState<number>(0);
  
  const [lastMonth, setLastMonth] = useState<boolean>(false);

  const [onActionCalendar, setOnActionCalendar] = useState<boolean>(true);

  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);
      }
    }).catch((e: any) => {
      if(e.response?.data?.error?.message){
        snackBar(e.response?.data?.error?.message);
        return;
      }
    }).finally(() => {
      let maxYearMonth = moment().format('YYYYMM');
      // let maxYearMonthValue = moment(maxYearMonth).format('YYYYMM');
      let newYearMonth = moment(yearMonth).add(1, 'month').format('YYYYMM');
     //  let newYearMonthValue = moment(newYearMonth).format('YYYYMM');
      if(parseInt(newYearMonth) <= parseInt(maxYearMonth)){
        setLastMonth(false);
      }
      else{
        setLastMonth(true);
      }
      setOnActionCalendar(true);
    });
  };

  const initialList = () => {
    // API 응답시간 문제로 초기화 한다
    setScheduledList([]);
    setCompletedList([]);
    setScheduledDateList([]);
    setCompletedDateList([]);
    setOnActionCalendar(false);
  };

  const onClickToMoveMonthPrev = () => {
    if(onActionCalendar){
      let newYearMonth = moment(yearMonth).subtract(1, 'month').format('YYYYMM');
      setYearMonth(newYearMonth);
      setYearMonth(newYearMonth);
      setFilterDate(0);
      initialList();
    }
  };
  const onClickToMoveMonthNext = () => {
    if(onActionCalendar){
      let maxYearMonth = moment().format('YYYYMM');
      let maxYearMonthValue = moment(maxYearMonth).format('YYYYMM');
      let newYearMonth = moment(yearMonth).add(1, 'month').format('YYYYMM');
      let newYearMonthValue = moment(newYearMonth).format('YYYYMM');
      if(parseInt(newYearMonthValue) <= parseInt(maxYearMonthValue)){
        setYearMonth(newYearMonth);
        setFilterDate(0);
        initialList();
      }
    }
  };
  const onClickToCalendarDate = (day: number) => {
    setFilterDate(day);
  };
  
  useEffect(() => {
    if(!!mid){
      callCalendar();
    }
  }, [yearMonth, mid]);

  return (
    <>
      <div className="calendar-wrap pt-30">
        <div className="input-wrapper top-select">
          <select 
            value={ mid }
            onChange={ (e: ChangeEvent<HTMLSelectElement>) => setMid(e.target.value) }
          >
          { 
            midOptions.map((value, index) => (
              <option
                key={ value.value }
                value={ value.value }
              >{ value.name }</option>
            )) 
          }
          </select>
        </div>
        
        <div className="month-group">
          <button
            className={ `month-btn ${(!onActionCalendar)? 'disabled': ''}` }
            aria-label={t('settlement.previousMonth')}
            onClick={ onClickToMoveMonthPrev }
          >
            <img
              src={ IMAGE_ROOT + '/ico_date_prev.svg' }
              alt={t('settlement.previous')}
            />
          </button>
          <div className="month-title">{ moment(yearMonth).format(i18n.language === 'ko' ? 'YYYY년 MM월' : 'YYYY MMM') }</div>
          <button
            className={ `month-btn ${(lastMonth || !onActionCalendar)? 'disabled': ''}` }
            aria-label={t('settlement.nextMonth')}
            onClick={ onClickToMoveMonthNext }
          >
            <img
              src={ IMAGE_ROOT + '/ico_date_next.svg' }
              alt={t('settlement.next')}
            />
          </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">{t('settlement.settlementCompleted')}</div>
          </div>
          <div className="legend-item">
            <div className="legend-dot scheduled"></div>
            <div className="legend-text">{t('settlement.depositScheduled')}</div>
          </div>
        </div>

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

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