import moment from 'moment';
import { useEffect, useState } from 'react';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { HomeMonthParams, HomeMonthResponse, HomeOverviewParams, HomeOverviewResponse, Sales, Settlement, TopPaymentMethodInfo, TopSalesDayInfo, TopSalesTimeInfo } from '../model/types';
import { useHomeOverviewMutation } from '../api/use-home-overview-mutation';
import { useHomeMonthwMutation } from '../api/use-home-month-mutation';
import { NumericFormat } from 'react-number-format';
import { useNavigate } from '@/shared/lib/hooks';
import { PATHS } from '@/shared/constants/paths';

export const BoxContainer2 = () => {
  const { navigate } = useNavigate();

  const [mid, setMid] = useState<string>('nictest001m');
  const [searchDate, setSearchDate] = useState<string>(moment().format('YYYY-MM-DD'));
  
  const [sales, setSales] = useState<Sales>();
  const [settlement, setSettlement] = useState<Settlement>();
  const [salesIncrease, setSalesIncrease] = useState<number>();
  const [settlementIncrease, setSettlementIncrease] = useState<number>();
  
  const [averageTransactionAmount, setAverageTransactionAmount] = useState<number>();
  const [dailyAverageSales, setDailyAverageSales] = useState<number>();
  const [dailyAverageCount, setDailyAverageCount] = useState<number>();
  const [topSalesDayInfo, setTopSalesDayInfo] = useState<TopSalesDayInfo>();
  const [topSalesTimeInfo, setTopSalesTimeInfo] = useState<TopSalesTimeInfo>();
  const [topPaymentMethodInfo, setTopPaymentMethodInfo] = useState<TopPaymentMethodInfo>();
  
  const { mutateAsync: homeMonth } = useHomeMonthwMutation();
  const { mutateAsync: homeOverview } = useHomeOverviewMutation();
  
  const callMonth = () => {
    let params: HomeMonthParams = {
      searchDate: searchDate,
      mid: mid,
    };
    homeMonth(params).then((rs: HomeMonthResponse) => {
      setSales(rs.sales);
      setSettlement(rs.settlement);

      let currentMonthAmount = rs.sales.currentMonthAmount;
      let previousMonthAmount = rs.sales.previousMonthAmount;
      if(currentMonthAmount && previousMonthAmount){
        let increase = (currentMonthAmount - previousMonthAmount) / previousMonthAmount * 100;
        setSalesIncrease(increase);
      }

      let currentMonthSettlementAmount = rs.settlement.currentMonthSettlementAmount;
      let previousMonthSettlementAmount = rs.settlement.previousMonthSettlementAmount;
      if(currentMonthSettlementAmount && previousMonthSettlementAmount){
        let increase = (currentMonthSettlementAmount - previousMonthSettlementAmount) / previousMonthSettlementAmount * 100;
        setSettlementIncrease(increase);
      }
    });
  };

  const callOverview = () => {
    let params: HomeOverviewParams = {
      searchDate: searchDate,
      mid: mid,
    };
    homeOverview(params).then((rs: HomeOverviewResponse) => {
      setAverageTransactionAmount(rs.averageTransactionAmount);
      setDailyAverageSales(rs.dailyAverageSales);
      setDailyAverageCount(rs.dailyAverageCount);
      setTopSalesDayInfo(rs.topSalesDayInfo);
      setTopSalesTimeInfo(rs.topSalesTimeInfo);
      setTopPaymentMethodInfo(rs.topPaymentMethodInfo);
    });
  };

  useEffect(() => {
    // callMonth();
    callOverview();
  }, []);

  const onClickToNavigate = () => {
    navigate(PATHS.settlement.list);
  };

  return (
    <>
      <div>
        <div className="section-header">
          <h3>매출/정산 현황</h3>
          <p>(전월 전체 매출/정산 대비 기준 )</p>
        </div>
        <div className="box-wrap two-sales">
          <h4>총 매출액</h4>
          <div className="today-sales mt-sty">
            <span className="won01">
              <NumericFormat
                value={ sales?.currentMonthAmount }
                thousandSeparator
                displayType="text"
                suffix='원'
              ></NumericFormat>
            </span>
            <span className={ `per ${(salesIncrease && salesIncrease >= 0)? 'plus': 'minus'}` }>
              <NumericFormat
                value={ salesIncrease }
                thousandSeparator
                displayType="text"
                prefix={ `${(salesIncrease && salesIncrease >= 0)? '↑ ': '↓ '}` }
                suffix='%'
              ></NumericFormat>
            </span>
            <a className="arrow">
              <img 
                src={ IMAGE_ROOT + '/ico_arrow.svg' } 
                alt="오늘 매출 바로가기" 
                onClick={ onClickToNavigate }
              />
            </a>
          </div>
        </div>
        <div className="box-wrap two-sales">
          <h4>총 정산액</h4>
          <div className="today-sales mt-sty">
            <span className="won02">
              <NumericFormat
                value={ settlement?.currentMonthSettlementAmount }
                thousandSeparator
                displayType="text"
                suffix='원'
              ></NumericFormat>
            </span>
            <span className={ `per ${(settlementIncrease && settlementIncrease >= 0)? 'plus': 'minus'}` }>
              <NumericFormat
                value={ settlementIncrease }
                thousandSeparator
                displayType="text"
                prefix={ `${(settlementIncrease && settlementIncrease >= 0)? '↑ ': '↓ '}` }
                suffix='%'
              ></NumericFormat>
            </span>
            <a className="arrow">
              <img 
                src={ IMAGE_ROOT + '/ico_arrow.svg' }
                alt="오늘 매출 바로가기"
                onClick={ onClickToNavigate }
              />
            </a>
          </div>
        </div>
      </div>
      <div>
        <div className="section-header">
          <h3>거래 인사이트</h3>
          <p>(최근 일주일 기준)</p>
        </div>
        <div className="box-wrap two-sales img-customer">
          <h4>평균 객단가</h4>
          <div className="two-account">
            <span>
              <NumericFormat
                value={ averageTransactionAmount }
                thousandSeparator
                displayType="text"
                suffix='원'
              ></NumericFormat>
            </span>
          </div>
        </div>
        <div className="box-wrap two-sales img-states">
          <h4>하루 평균 매출 및 건수</h4>
          <div className="two-account">
            <span>
              <NumericFormat
                value={ dailyAverageSales }
                thousandSeparator
                displayType="text"
                suffix='원'
              ></NumericFormat>
              (<NumericFormat
                value={ dailyAverageCount }
                thousandSeparator
                displayType="text"
                suffix='원'
              ></NumericFormat>)
            </span>
          </div>
        </div>
      </div>
      <div>
        <div className="box-wrap ranking">
          <h4>매출이 가장 높은 요일</h4>
          <ul>
            {
              topSalesDayInfo?.daySalesRatios.map((value, index) => (
                <li key={`key-day-sales-ratio-${index}`}>
                  <span className={ `ranking-num-${(index === 0)? '01': 'ot'}` }>{ (index + 1) }</span>
                  <span>{ value.dayOfWeek }</span>
                  <span className="last-per-01">{ value.ratio + '%' }</span>
                </li>
              ))
            }
          </ul>
        </div>
        <div className="box-wrap ranking">
          <h4>매출이 가장 높은 시간</h4>
          <ul>
            {
              topSalesTimeInfo?.timeSalesRatios.map((value, index) => (
                <li key={`key-time-sales-ratio-${index}`}>
                  <span className={ `ranking-num-${(index === 0)? '01': 'ot'}` }>{ (index + 1) }</span>
                  <span>{ value.hour }</span>
                  <span className="last-per-01">{ value.ratio + '%' }</span>
                </li>
              ))
            }
          </ul>
        </div>
        <div className="box-wrap ranking">
          <h4>가장 많이쓰인 결제 수단</h4>
          <ul>
            {
              topPaymentMethodInfo?.paymentMethodRatios.map((value, index) => (
                <li key={`key-payment-method-ratio-${index}`}>
                  <span className={ `ranking-num-${(index === 0)? '01': 'ot'}` }>{ (index + 1) }</span>
                  <span>{ value.paymentMethod }</span>
                  <span className="last-per-01">{ value.ratio + '%' }</span>
                </li>
              ))
            }
          </ul>
        </div>
      </div>
    </>
  );
};
