import moment from 'moment';
import { useEffect, useState } from 'react';
import { useStore } from '@/shared/model/store';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { EscrowList } from '@/entities/transaction/ui/escrow-list';
import { EscrowListItem, TransactionCategory, SortByKeys, EscrowDeliveryStatus, EscrowSearchType, EscrowSettlementStatus } from '@/entities/transaction/model/types';
import { useEscrowListMutation } from '@/entities/transaction/api/use-escrow-list-mutation';
import { useDownloadExcelMutation } from '@/entities/transaction/api/use-download-excel-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constants';
import { EscrowFilter } from '@/entities/transaction/ui/filter/escrow-filter';
import { EscrowDeliveryStatusBtnGroup } from '@/entities/transaction/model/contant';
import { SortOptionsBox } from '@/entities/transaction/ui/sort-options-box';
import { HeaderType } from '@/entities/common/model/types';
import { 
	useSetOnBack,
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';

export const EscrowListPage = () => {
	const { navigate } = useNavigate();
	const userInfo = useStore((state) => state.UserStore.UserInfo);

	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>('nictest001m');
	const [searchType, setSearchType] = useState<EscrowSearchType>(EscrowSearchType.ALL);
	const [searchKeyword, setSearchKeyword] = useState<string>('');
	//const [startDate, setStartDate] = useState(moment().subtract(1, 'month').format('YYYY-MM-DD'));
	const [startDate, setStartDate] = useState(moment().format('YYYY-MM-DD'));
	const [endDate, setEndDate] = useState(moment().format('YYYY-MM-DD'));
	const [deliveryStatus, setDeliveryStatus] = useState<EscrowDeliveryStatus>(EscrowDeliveryStatus.ALL);
	const [settlementStatus, setSettlementStatus] = useState<EscrowSettlementStatus>(EscrowSettlementStatus.ALL);
	const [minAmount, setMinAmount] = useState<number | string>();
	const [maxAmount, setMaxAmount] = useState<number | string>();	
		
	useSetHeaderTitle('에스크로');
	useSetHeaderType(HeaderType.LeftArrow);
	useSetOnBack(() => {
		navigate(PATHS.home);
	});
  useSetFooterMode(true);

	const { mutateAsync: escrowList } = useEscrowListMutation();
	const { mutateAsync: downloadExcel } = useDownloadExcelMutation();
	
	const callList = (option?: {
    sortBy?: string, 
    val?: string
  }) => {
		pageParam.sortBy = (option?.sortBy)? option.sortBy: sortBy;
    setPageParam(pageParam);
		let newMinAmount = minAmount;
		if(!!minAmount && typeof(minAmount) === 'string'){
			newMinAmount = parseInt(minAmount);
		}
		let newMaxAmount = maxAmount;
		if(!!maxAmount && typeof(maxAmount) === 'string'){
			newMaxAmount = parseInt(maxAmount);
		}
    let listParams = {
      mid: mid,
  		searchType: 'ORDER_NUMBER',
  		searchKeyword: searchKeyword,
  		startDate: startDate,
  		endDate: endDate,
  		deliveryStatus: deliveryStatus,
  		settlementStatus: settlementStatus,
  		minAmount: newMinAmount,
  		maxAmount: newMaxAmount,
			pagination: pageParam
    };

		escrowList(listParams).then((rs) => {
      setListItems(assembleData(rs.content));
    });
  };

	const assembleData = (content: Array<EscrowListItem>) => {
    let data: any = {};
    if(content && content.length > 0){
      for(let i=0;i<content?.length;i++){
        let groupDate = moment(content[i]?.transactionDateTime).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 onClickToDeliveryStatus = (val: EscrowDeliveryStatus) => {
    setDeliveryStatus(val);
    callList({val: val});
  };

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

	return (
		<>
			<main>
				<div className="tab-content">
					<div className="tab-pane sub active">
						<div className="summary-section">
							<div className="credit-controls">
								<div>
									<input 
										type="text" 
										className="credit-period" 
										value={ moment(startDate).format('YYYY.MM.DD') + '-' + moment(endDate).format('YYYY.MM.DD') } 
										readOnly={ true } 
									/>
									<button className="filter-btn">
										<img 
											src={ IMAGE_ROOT + '/ico_setting.svg' } 
											alt="검색옵션"
											onClick={ () => onClickToOpenFilter() }
										/>
									</button>
								</div>
								<button className="download-btn">
									<img 
										src={ IMAGE_ROOT + '/ico_download.svg' } 
										alt="다운로드"
										onClick={ () => onClickToDownloadExcel() }
                  />
								</button>
							</div>
						</div>
							
						<div className="filter-section">
							<SortOptionsBox
								sortBy={ sortBy }
								onCliCkToSort={ onCliCkToSort }
							></SortOptionsBox>
							<div className="excrow">
								<div className="full-menu-keywords no-padding">
								{
									EscrowDeliveryStatusBtnGroup.map((value, index) => (
										<span 
											key={ `key-service-code=${ index }` }
											className={ `keyword-tag ${(deliveryStatus === value.value)? 'active': ''}` }
											onClick={ () => onClickToDeliveryStatus(value.value) }
										>{ value.name }</span>
									))
								}
								</div>
							</div>
						</div>
						<EscrowList 
							listItems={ listItems }
							transactionCategory={ TransactionCategory.Escrow }
						></EscrowList> 
					</div>
				</div>
			</main>
			<EscrowFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
				mid={ mid }
				searchType={ searchType }
				searchKeyword={searchKeyword }
				startDate={ startDate }
				endDate={ endDate }
				deliveryStatus={ deliveryStatus }
				settlementStatus={ settlementStatus }
				minAmount={ minAmount }
				maxAmount={ maxAmount }
				setMid={ setMid }
				setSearchType={ setSearchType }
				setSearchKeyword={ setSearchKeyword }
				setStartDate={ setStartDate }
				setEndDate={ setEndDate }
				setDeliveryStatus={ setDeliveryStatus }
				setSettlementStatus={ setSettlementStatus }
				setMinAmount={ setMinAmount }
				setMaxAmount={ setMaxAmount }
      ></EscrowFilter>
		</>
	);
};