import moment from 'moment';
import { NumericFormat } from 'react-number-format';
import { useEffect, useState } from 'react';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useHomeTodayMutation } from '../api/use-home-today-mutation';
import {
  HomeTodayParams,
  HomeTodayResponse,
  Sales,
  Settlement
} from '../model/types';
import { useNavigate } from '@/shared/lib/hooks';
import { PATHS } from '@/shared/constants/paths';
import { useStore } from '@/shared/model/store';
import { useTranslation } from 'react-i18next';

export const BoxContainer1 = () => {
  const { navigate } = useNavigate();
  const { t, i18n } = useTranslation();
  const userMid = useStore.getState().UserStore.mid;

  const [mid, setMid] = useState<string>(userMid);
  const [searchDate, setSearchDate] = useState<string>(moment().format('YYYYMMDD'));

  const [sales, setSales] = useState<Sales>();
  const [settlement, setSettlement] = useState<Settlement>();
  const [increaseRate, setIncreaseRate] = useState<number>();
  const [availableLimit, setAvailableLimit] = useState<number>(100);

  const { mutateAsync: homeToday } = useHomeTodayMutation();
  
  const callToday = () => {
    let params: HomeTodayParams = {
      searchDate: searchDate,
      mid: mid,
    };
    homeToday(params).then((rs: HomeTodayResponse) => {
      setSales(rs.sales);

      let yesterdayTotalAmount = rs.sales.yesterdayTotalAmount;
      let todayTotalAmount = rs.sales.todayTotalAmount;
      if(todayTotalAmount && yesterdayTotalAmount){
        let rate = ((todayTotalAmount / yesterdayTotalAmount) - 1) * 100;
        let roundRate = Math.round(rate * 10) / 10;
        setIncreaseRate(roundRate);
      }

      let totalCreditLimit = rs.settlement.totalCreditLimit;
      let availableCredit = rs.settlement.availableCredit;
      if(totalCreditLimit && availableCredit){
        let rate = (availableCredit / totalCreditLimit) * 100;
        let roundRate = Math.round(rate * 10) / 10;
        setAvailableLimit(roundRate);
      }      
      
      setSettlement(rs.settlement);
    });
  };

  const onClickToNavigate = () => {
    navigate(PATHS.settlement.list);
  };
    
  useEffect(() => {
    callToday();
  }, []);
  
  return (
    <>
      <div className="box-wrap">
        <h3>{t('home.todaySales')}</h3>
        <div className="today-sales">
          <span className="won01">
            {t('home.money', { value: new Intl.NumberFormat('en-US').format(sales?.todayTotalAmount || 0) })}
          </span>
          <span className={ `per ${(increaseRate && increaseRate >= 0)? 'plus': 'minus'}` }>
            <NumericFormat
              value={ increaseRate }
              thousandSeparator
              displayType="text"
              prefix={ `${(increaseRate && increaseRate >= 0)? '↑ ': '↓ '}` }
              suffix='%'
            ></NumericFormat>
          </span>
          <a className="arrow">
            <img
              src={ IMAGE_ROOT + '/ico_arrow.svg' }
              alt={t('home.goToSales')}
              onClick={ onClickToNavigate }
            />
          </a>
        </div>
        <ul className="dales-detail">
          <li className="approve">
            {t('home.approvalCount')}
            <strong style={{marginLeft: '4px'}}>
              <NumericFormat
                value={ sales?.totalCount }
                thousandSeparator
                displayType="text"
                suffix={t('home.count')}
              ></NumericFormat>
            </strong>
          </li>
          <li className="cancel">
            {t('home.cancelCount')}
            <strong style={{marginLeft: '4px'}}>
              <NumericFormat
                value={ sales?.cancelCount }
                thousandSeparator
                displayType="text"
                suffix={t('home.count')}
              ></NumericFormat>
            </strong>
          </li>
        </ul>
      </div>
      <div className="box-wrap">
        <h3>{t('home.todaySettlement')}</h3>
        <div className="today-sales">
          <span className="won02">
            {t('home.money', { value: new Intl.NumberFormat('en-US').format(settlement?.todaySettlementAmount || 0) })}
          </span>
          <span className="per">{t('home.depositCompleted')}</span>
          <a className="arrow">
            <img
              src={ IMAGE_ROOT + '/ico_arrow.svg' }
              alt={t('home.goToSales')}
              onClick={ onClickToNavigate }
            />
          </a>
        </div>
        <div className="progressbar">
          <div className="progress-header">
            <span className="progress-title">{t('home.settlementLimit')}</span>
            <span className="progress-remaining">
              <NumericFormat
                value={ availableLimit }
                thousandSeparator
                displayType="text"
                suffix={t('home.percentRemaining')}
              ></NumericFormat>
            </span>
          </div>
          <div className="progress-container">
            <div className="progress-bar">
              <div className="progress-fill" style={{width: (100 - (availableLimit || 0)) +'px' }}></div>
            </div>
          </div>
          <div className="remain-limit">
            <span>{t('home.remainingSettlementLimit')}</span>
            <strong style={{marginLeft: '4px'}}>
              {t('home.money', { value: new Intl.NumberFormat('en-US').format(settlement?.availableCredit || 0) })}
            </strong>
          </div>
        </div>
      </div>
    </>
  );
};
