import moment from 'moment';
import { useEffect, useState } from 'react';
import { NumericFormat } from 'react-number-format';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { ListDateGroup } from './list-date-group';
import { ListItem, ListDateGroupProps, SortByKeys } from '@/entities/settlement/model/types';
import { useSettlementListMutation } from '@/entities/settlement/api/use-settlement-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constants';
import { SortOptionsBox } from '@/entities/transaction/ui/sort-options-box';

export const ListWrap = () => {
  const [selectedServiceCode, setSelectedServiceCode] = useState<string>('st');
  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState<ListDateGroupProps>({});
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [fromDate, setFromDate] = useState(moment().subtract(1, 'month').format('YYYYMMDD'));
  const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
    
  const { mutateAsync: settlementList } = useSettlementListMutation();

  const callList = (option?: {
    sortBy?: string, 
    val?: string
  }) => {
    let listSummaryParams = {
      moid: 'string',
      tid: 'string',
      fromDate: fromDate,
      toDate: toDate,
      stateCode: '0',
      serviceCode: (option?.val)? option.val: selectedServiceCode,
      minAmount: 0,
      maxAmount: 0,
      dateCl: 'TRANS',
      goodsName: 'string',
      cardCode: 'st',
      bankCode: 'str',
      searchCl: 'CARD_NO',
      searchValue: 'string',
    };
    pageParam.sortBy = (option?.sortBy)? option.sortBy: sortBy;
    setPageParam(pageParam);
    
    let listParams = {
      ...listSummaryParams,
      ...{page: pageParam}
    };
    settlementList(listParams).then((rs) => {
      setListItems(assembleData(rs.content));
    });
  };

  const assembleData = (content: Array<ListItem>) => {
    let data: any = {};
    if(content && content.length > 0){
      for(let i=0;i<content?.length;i++){
        let stateDate = content[i]?.stateDate;
        let groupDate = stateDate?.substring(0, 8);
        if(!!groupDate && !data.hasOwnProperty(groupDate)){
          data[groupDate] = [];
        }
        if(!!groupDate && data.hasOwnProperty(groupDate)){
          data[groupDate].push(content[i]);
        }
      }
    }
    return data;
  };
  const onCliCkToSort = (sort: SortByKeys) => {
    setSortBy(sort);
    callList({sortBy: sort});
  };
  useEffect(() => {
    callList();
  }, []);

  const getListDateGroup = () => {
    let rs = [];
    if(Object.keys(listItems).length > 0){
      for (const [key, value] of Object.entries(listItems)) {
        rs.push(
          <ListDateGroup
            key={ key }
            date={ key }
            items={ value }
          ></ListDateGroup>
        );  
      }
    }
    return rs;
  };

  return (
    <>
      <div className="summary-section pt-30">
        <div className="credit-controls">
          <div>
            <input 
              className="credit-period" 
              type="text" 
              value="2025.06.01 ~ 2025.06.31" 
              readOnly={ true }
            />
            <button className="filter-btn">
              <img 
                src={ IMAGE_ROOT + '/ico_setting.svg' } 
                alt="검색옵션"
              />
            </button>
          </div>
          <button className="download-btn">
            <img 
              src={ IMAGE_ROOT + '/ico_download.svg' }
              alt="다운로드"
            />
          </button>
        </div>
        <div className="summary-label label">정산금액</div>
        <div className="summary-amount divTop">
          <span className="amount-text">
            <NumericFormat
              value={ '83745200' } 
              thousandSeparator
              displayType="text"
              suffix={ '원' }
            ></NumericFormat>
          </span>
          <button>
            <img 
              src={ IMAGE_ROOT + '/ico_divTop_arrow.svg' } 
              alt="화살표"
            />
          </button>
        </div>
        <div className="summary-extend">
          <ul className="summary-amount-list">
            <li className="summary-amount-item">
              <span className="label">거래금액</span>
              <span className="value">
                <NumericFormat
                  value={ '67860120' } 
                  thousandSeparator
                  displayType="text"
                ></NumericFormat> <span className="unit">원</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">PG수수료</span>
              <span className="value minus">
                <NumericFormat
                  value={ '-2409428' } 
                  thousandSeparator
                  displayType="text"
                ></NumericFormat> <span className="unit">원</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">보류</span>
              <span className="value">
                <NumericFormat
                  value={ '0' } 
                  thousandSeparator
                  displayType="text"
                ></NumericFormat> <span className="unit">원</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">해제</span>
              <span className="value link">
                <NumericFormat
                  value={ '5000' } 
                  thousandSeparator
                  displayType="text"
                ></NumericFormat> <span className="unit">원</span>
              </span>
            </li>
            <li className="summary-amount-item">
              <span className="label">상계</span>
              <span className="value minus">
                <NumericFormat
                  value={ '-388393' } 
                  thousandSeparator
                  displayType="text"
                ></NumericFormat> <span className="unit">원</span>
              </span>
            </li>
          </ul>
        </div>
      </div>

      <div className="filter-section">
        <SortOptionsBox
          sortBy={ sortBy }
          onCliCkToSort={ onCliCkToSort }
        ></SortOptionsBox>
        <div>
          <div className="full-menu-keywords no-padding">
            <span className="keyword-tag active">거래건별 보기</span>
            <span className="keyword-tag">정산내역</span>
          </div>
        </div>
      </div>
      <div className="transaction-list">
        { 
          (!!listItems && Object.keys(listItems).length > 0) &&
            getListDateGroup() 
        }
      </div>
    </>
  );
};