import moment from 'moment';
import { ChangeEvent, useEffect, useState } from 'react';
import { NumericFormat } from 'react-number-format';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { AllTransactionList } from '@/entities/transaction/ui/all-transaction-list';
import { AllTransactionListItem, TransactionCategory, SortByKeys } from '@/entities/transaction/model/types';
import { useAllTransactionListMutation } from '@/entities/transaction/api/use-all-transaction-list-mutation';
import { useAllTransactionListSummaryMutation } from '@/entities/transaction/api/use-all-transaction-list-summary-mutation';
import { useDownloadExcelMutation } from '@/entities/transaction/api/use-download-excel-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constants';
import { Filter } from '@/entities/transaction/ui/filter';
import { SortOptionsBox } from '@/entities/transaction/ui/sort-options-box';
import { FooterItemActiveKey } from '@/entities/common/model/types';
import { HeaderType } from '@/entities/common/model/types';
import { 
	useSetOnBack,
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode,
  useSetFooterCurrentPage
} from '@/widgets/sub-layout/use-sub-layout';

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

  const [serviceCodeOptions, setServiceCodeOptions] = useState<Array<Record<string, any>>>();
  const [selectedServiceCode, setSelectedServiceCode] = useState<string>('st');
  const [sortBy, setSortBy] = useState<SortByKeys>(SortByKeys.New);
  const [listItems, setListItems] = useState({});
  const [totalTransactionCount, setTotalTransactionCount] = useState<number>(0);
  const [totalTransactionAmount, setTotalTransactionAmount] = useState<number>(0);
  const [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [fromDate, setFromDate] = useState(moment().subtract(1, 'month').format('YYYYMMDD'));
  const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
  
	useSetHeaderTitle('거래내역 조회');
	useSetHeaderType(HeaderType.LeftArrow);
	useSetOnBack(() => {
		navigate(PATHS.home);
	});
	useSetFooterMode(true);
  useSetFooterCurrentPage(FooterItemActiveKey.Transaction);

  const { mutateAsync: allTransactionList } = useAllTransactionListMutation();
  const { mutateAsync: allTransactionListSummary } = useAllTransactionListSummaryMutation();
  const { mutateAsync: downloadExcel } = useDownloadExcelMutation();
  
  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}
    };
    allTransactionList(listParams).then((rs) => {
      setListItems(assembleData(rs.content));
    });
    allTransactionListSummary(listSummaryParams).then((rs) => {
      setTotalTransactionAmount(rs.totalTransactionAmount);
      setTotalTransactionCount(rs.totalTransactionCount);
    });
  };

  const assembleData = (content: Array<AllTransactionListItem>) => {
    let data: any = {};
    if(content && content.length > 0){
      for(let i=0;i<content?.length;i++){
        let stateDate = content[i]?.stateDate?.substring(0, 8);
        let groupDate = moment(stateDate).format('YYYYMMDD');
        if(!!groupDate && !data.hasOwnProperty(groupDate)){
          data[groupDate] = [];
        }
        if(!!groupDate && data.hasOwnProperty(groupDate)){
          data[groupDate].push(content[i]);
        }
      }
    }
    return data;
  };
  
  const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToDownloadExcel = () => {
    // tid??? 확인 필요
    downloadExcel({
      // tid: tid
    }).then((rs) => {

    });
  };
  const onCliCkToSort = (sort: SortByKeys) => {
    setSortBy(sort);
    callList({sortBy: sort});
  };
  const callServiceCodeOptions = () => {
    let options = [
      {text: '계좌간편결제', value: 'simple'},
      {text: '신용카드', value: 'card'},
      {text: '계좌이체', value: 'transfer'},
      {text: '휴대폰', value: 'phone'},
      {text: '문화상품권', value: 'gift'},
      {text: '티머니페이', value: '티머니페이'},  
    ];
    setServiceCodeOptions(options);
    setSelectedServiceCode('simple');  
  };

  const onChangeSelectedServiceCode = (e: ChangeEvent<HTMLSelectElement>) => {
    let val = e.target.value;
    // onchagne 에서 useState가 즉시 반영 안되므로 값을 직접 바로 넘긴다.
    setSelectedServiceCode(val);
    callList({val: val});
  };

  const getServiceCodeOptions = () => {
    let rs = [];
    if(!!serviceCodeOptions && serviceCodeOptions.length > 0)
    for(let i=0;i<serviceCodeOptions.length;i++){
      rs.push(
        <option 
          key={`key-${i}`}
          value={serviceCodeOptions[i]?.value}
        >{ serviceCodeOptions[i]?.text }</option>
      )
    }
    return rs;
  };

  useEffect(() => {
    callServiceCodeOptions();
    callList();
  }, []);

	return (
		<>
			<main>
				<div className="tab-content">
					<div className="tab-pane sub active">
						<div className="summary-section">
							<div className="summary-label">조회금액</div>
							<div className="summary-amount">
								<span className="amount-text">
                  <NumericFormat
                    value={ totalTransactionAmount } 
                    thousandSeparator
                    displayType="text"
                    suffix={ '원' }
                  ></NumericFormat> 
                </span>
								<div className="summary-actions">
									<button className="filter-btn">
										<img 
                      src={ IMAGE_ROOT + '/ico_setting.svg' } 
                      alt="검색옵션"
                      onClick={ () => onClickToOpenFilter() }
                    />
									</button>
									<button className="download-btn">
										<img 
                      src={ IMAGE_ROOT + '/ico_download.svg' } 
                      alt="다운로드"
                      onClick={ () => onClickToDownloadExcel() }
                    />
									</button>
								</div>
							</div>
							<div className="summary-details">
								<div className="detail-item">
									<span className="detail-label">조회일자</span>
									<span className="detail-value">{ moment(fromDate).format('YYYY.MM.DD') } ~ { moment(toDate).format('YYYY.MM.DD') }</span>
								</div>
								<div className="detail-item">
									<span className="detail-label">거래건수</span>
									<span className="detail-value">
                    <NumericFormat
                      value={ totalTransactionCount } 
                      thousandSeparator
                      displayType="text"
                      prefix={ '총 ' }
                      suffix={ ' 건' }
                    ></NumericFormat>
                  </span>
								</div>
							</div>
						</div>
							
						<div className="filter-section">
							<SortOptionsBox
                sortBy={ sortBy }
                onCliCkToSort={ onCliCkToSort }
              ></SortOptionsBox>
							<select 
                value={ selectedServiceCode }
                onChange={ (e) => onChangeSelectedServiceCode(e) }>
                { getServiceCodeOptions() }
							</select>
						</div>
            <AllTransactionList 
              listItems={ listItems }
              transactionCategory={ TransactionCategory.AllTransaction }
            ></AllTransactionList> 
					</div>
				</div>
			</main>
      <Filter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
      ></Filter>
    </>
	);
};