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, AllTransactionStateCode, AllTransactionServiceCode, AllTransactionSearchCl } 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/constant';
import { AllTransactionFilter } from '@/entities/transaction/ui/filter/all-transaction-filter';
import { SortOptionsBox } from '@/entities/common/ui/sort-options-box';
import { FooterItemActiveKey } from '@/entities/common/model/types';
import { SortByKeys, 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 [filterOn, setFilterOn] = useState<boolean>(false);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  const [mid, setMid] = useState<string>('nictest00m');
  const [moid, setMoid] = useState<string>('');
  const [tid, setTid] = useState<string>('');
  // const [fromDate, setFromDate] = useState(moment().subtract(1, 'month').format('YYYYMMDD'));
  const [fromDate, setFromDate] = useState(moment().format('YYYYMMDD'));
  const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
  const [stateCode, setStateCode] = useState<AllTransactionStateCode>(AllTransactionStateCode.ALL);
  const [serviceCode, setServiceCode] = useState<AllTransactionServiceCode>(AllTransactionServiceCode.ALL);
  const [minAmount, setMinAmount] = useState<number>();
	const [maxAmount, setMaxAmount] = useState<number>();
  const [cardCode, setCardCode] = useState<string | undefined>();
  const [bankCode, setBankCode] = useState<string | undefined>();
  const [searchCl, setSearchCl] = useState<AllTransactionSearchCl | undefined>();
  const [searchValue, setSearchValue] = useState<string | undefined>();

  const [totalTransactionCount, setTotalTransactionCount] = useState<number>(0);
  const [totalTransactionAmount, setTotalTransactionAmount] = useState<number>(0);
  
  
  
	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: moid,
      tid: tid,
      fromDate: fromDate,
      toDate: toDate,
      stateCode: stateCode,
      serviceCode: serviceCode,
      minAmount: minAmount,
      maxAmount: maxAmount,
      dateCl: 'TRANS',
      goodsName: 'string',
      cardCode: cardCode,
      bankCode: bankCode,
      searchCl: searchCl,
      searchValue: searchValue,
    };
    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>
      <AllTransactionFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
        mid={ mid }
        fromDate={ fromDate }
        toDate={ toDate }
        stateCode={ stateCode }
        serviceCode={ serviceCode }
        minAmount={ minAmount }
        maxAmount={ maxAmount }
        cardCode={ cardCode }
        bankCode={ bankCode }
        searchCl={ searchCl }
        searchValue={ searchValue }
        setMid={ setMid }
        setMoid={ setMoid }
        setTid={ setTid }
        setFromDate={ setFromDate }
        setToDate={ setToDate }
        setStateCode={ setStateCode }
        setServiceCode={ setServiceCode }
        setMinAmount={ setMinAmount }
        setMaxAmount={ setMaxAmount }
        setCardCode={ setCardCode }
        setBankCode={ setBankCode }
        setSearchCl={ setSearchCl }
        setSearchValue={ setSearchValue }
      ></AllTransactionFilter>
    </>
	);
};