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 { 
	TransactionCategory, 
	EscrowDeliveryStatus, 
	EscrowSearchType, 
	EscrowSettlementStatus, 
	ListItemProps, 
	EscrowListParams,
	EscrowListResponse
} 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/constant';
import { EscrowFilter } from '@/entities/transaction/ui/filter/escrow-filter';
import { EscrowDeliveryStatusBtnGroup } from '@/entities/transaction/model/contant';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { SortTypeKeys, HeaderType, DefaultRequestPagination } from '@/entities/common/model/types';
import { 
	useSetOnBack,
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';

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

	const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
	const [listItems, setListItems] = useState<Array<ListItemProps>>([]);
	const [filterOn, setFilterOn] = useState<boolean>(false);
	const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
	const [mid, setMid] = useState<string>(userMid);
	const [searchType, setSearchType] = useState<EscrowSearchType>(EscrowSearchType.ALL);
	const [searchKeyword, setSearchKeyword] = useState<string>('');
	const [startDate, setStartDate] = useState(moment().subtract(1, 'month').format('YYYYMMDD'));
	// const [startDate, setStartDate] = useState(moment().format('YYYYMMDD'));
	const [endDate, setEndDate] = useState(moment().format('YYYYMMDD'));
	const [deliveryStatus, setDeliveryStatus] = useState<EscrowDeliveryStatus>(EscrowDeliveryStatus.ALL);
	const [settlementStatus, setSettlementStatus] = useState<EscrowSettlementStatus>(EscrowSettlementStatus.ALL);
	const [minAmount, setMinAmount] = useState<number>();
	const [maxAmount, setMaxAmount] = useState<number>();

	const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);
		
	useSetHeaderTitle('에스크로');
	useSetHeaderType(HeaderType.LeftArrow);
	useSetOnBack(() => {
		navigate(PATHS.home);
	});
  useSetFooterMode(false);

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

		if(listParams.page){
			listParams.page.sortType = option?.sortType || sortType;
    	setPageParam(listParams.page);
		}

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

	const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToDownloadExcel = () => {
    setEmailBottomSheetOn(true);
  };
	const onRequestDownloadExcel = (userEmail?: string) => {
    // tid??? 확인 필요
    /*
    downloadExcel({
      // tid: tid
    }).then((rs) => {

    });
    */
  };
  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
    callList({
			sortType: sort
		});
  };
	
	const onClickToDeliveryStatus = (val: EscrowDeliveryStatus) => {
    setDeliveryStatus(val);
    callList({
			val: val
		});
  };

  useEffect(() => {
    callList();
  }, []);
	useEffect(() => {
		callList();
	}, [
		mid, searchType, searchKeyword,
		startDate, endDate,
		deliveryStatus, settlementStatus,
		minAmount, maxAmount
	]);

	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">
							<SortTypeBox
								sortType={ sortType }
								onClickToSort={ onClickToSort }
							></SortTypeBox>
							<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>
			{ !!emailBottomSheetOn &&
				<EmailBottomSheet
					bottomSheetOn={ emailBottomSheetOn }
					setBottomSheetOn={ setEmailBottomSheetOn }
					imageSave={ false }
					sendEmail={ true }
					sendRequest={ onRequestDownloadExcel }
				></EmailBottomSheet>
			}
		</>
	);
};