import moment from 'moment';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDetailOnStore, useDownloadBottomSheetOnStore, useFilterlOnStore, 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 { BillingList } from '@/entities/transaction/ui/billing-list';
import { 
	TransactionCategory, 
	BillingRequestStatus, 
	BillingProcessResult, 
	BillingPaymentMethod, 
	BillingSearchType, 
	ListItemProps, 
	BillingListParams, 
	BillingListResponse, 
	DetailData,
	BillingExcelParams
} from '@/entities/transaction/model/types';
import { useBillingListMutation } from '@/entities/transaction/api/use-billing-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { BillingFilter } from '@/entities/transaction/ui/filter/billing-filter';
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { getBillingRequestStatusBtnGroup } from '@/entities/transaction/model/contant';
import { SortTypeKeys, HeaderType, DefaultRequestPagination } from '@/entities/common/model/types';
import { 
	useSetOnBack,
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';
import { DownloadBottomSheet, DownloadSelectedMode } from '@/entities/common/ui/download-bottom-sheet';
import useIntersectionObserver from '@/widgets/intersection-observer';
import { BillingDetail } from '@/entities/transaction/ui/detail/billing-detail';
import { showAlert } from '@/widgets/show-alert';
import { checkGrant } from '@/shared/lib/check-grant';
import { snackBar } from '@/shared/lib';
import { useBillingExcelMutation } from '@/entities/transaction/api/use-billing-excel-mutation';

/* 빌링 34 */
const menuId = 34;
const defaultParams = {
	searchType: BillingSearchType.ALL,
	searchKeyword: '',
	startDate: moment().format('YYYYMMDD'),
	endDate: moment().format('YYYYMMDD'),
	requestStatus: BillingRequestStatus.ALL,
	processResult: BillingProcessResult.ALL,
	paymentMethod: BillingPaymentMethod.ALL,
	minAmount: undefined,
	maxAmount: undefined
};
export const BillingListPage = () => {
	const { navigate } = useNavigate();
	const { t } = useTranslation();
	const userMid = useStore.getState().UserStore.mid;
	
	const [onActionIntersect, setOnActionIntersect] = useState<boolean>(false);
	const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
	const [listItems, setListItems] = useState<Array<ListItemProps>>([]);
	const { filterOn, setFilterOn } = useFilterlOnStore();
	const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);
	const [mid, setMid] = useState<string>(userMid);
	const [searchType, setSearchType] = useState<BillingSearchType>(defaultParams.searchType);
	const [searchKeyword, setSearchKeyword] = useState<string>(defaultParams.searchKeyword);
	const [startDate, setStartDate] = useState<string>(defaultParams.startDate);
	const [endDate, setEndDate] = useState<string>(defaultParams.endDate);
	const [requestStatus, setRequestStatus] = useState<BillingRequestStatus>(defaultParams.requestStatus);
	const [processResult, setProcessResult] = useState<BillingProcessResult>(defaultParams.processResult);
	const [paymentMethod, setPaymentMethod] = useState<BillingPaymentMethod>(defaultParams.paymentMethod);
	const [minAmount, setMinAmount] = useState<number | undefined>(defaultParams.minAmount);
	const [maxAmount, setMaxAmount] = useState<number | undefined>(defaultParams.maxAmount);

	const { downloadBottomSheetOn, setDownloadBottomSheetOn } = useDownloadBottomSheetOnStore();

	const { detailOn, setDetailOn } = useDetailOnStore();
  const [detailTid, setDetailTid] = useState<string>('');

	const [filterUsed, setFilterUsed] = useState<boolean>(false);

	useSetHeaderTitle(t('billing.title'));
	useSetHeaderType(HeaderType.LeftArrow);
	useSetOnBack(() => {
		navigate(PATHS.home);
	});
  useSetFooterMode(false);

	const { mutateAsync: billingList } = useBillingListMutation();
	const { mutateAsync: billingExcel } = useBillingExcelMutation();

	const onIntersect: IntersectionObserverCallback = (entries: Array<IntersectionObserverEntry>) => {
    entries.forEach((entry: IntersectionObserverEntry) => {
      if(entry.isIntersecting){
        if(onActionIntersect && !!pageParam.cursor){
					setOnActionIntersect(false);
          callList('page');
        } 
      }
    });
  };

	const { setTarget } = useIntersectionObserver({ 
    threshold: 1, 
    onIntersect 
  });

	const callList = (type?: string) => {
		setOnActionIntersect(false);
		let listParams: BillingListParams = {
      mid: mid,
      searchType: searchType,
			searchKeyword: searchKeyword,
      startDate: startDate,
      endDate: endDate,
      requestStatus: requestStatus,
      processResult: processResult,
      paymentMethod: paymentMethod,
			minAmount: minAmount,
			maxAmount: maxAmount,
			page: {
				...pageParam,
				...{ sortType: sortType }
			}
    };
		if(type !== 'page' && listParams.page){
      listParams.page.cursor = null;
    }
				    
    billingList(listParams).then((rs: BillingListResponse) => {
      if(type === 'page'){
        setListItems([
          ...listItems,
          ...rs.content
        ]);
      }
      else{
        setListItems(rs.content);
      }
			if(rs.hasNext 
				&& rs.nextCursor !== pageParam.cursor
        && rs.content.length === DEFAULT_PAGE_PARAM.size
      ){
        setPageParam({
          ...pageParam,
          ...{ cursor: rs.nextCursor }
        });
      }
      else{
        setPageParam({
          ...pageParam,
          ...{ cursor: null }
        });
			}
			setOnActionIntersect(
        !!rs.hasNext 
				&& rs.nextCursor !== pageParam.cursor
        && rs.content.length === DEFAULT_PAGE_PARAM.size
      );
    }).catch((e: any) => {
      if(e.response?.data?.error?.message){
        snackBar(e.response?.data?.error?.message);
        return;
      }
    });
	}
	
	const onClickToOpenFilter = () => {
    setFilterOn(!filterOn);
  };
  const onClickToOpenDownloadBottomSheet = () => {
		if(checkGrant(menuId, 'D')){
    	setDownloadBottomSheetOn(true);
		}
		else{
			showAlert(t('common.nopermission'));
		}
  };
  const onClickToSort = (sort: SortTypeKeys) => {
    setSortType(sort);
  };

	const onClickToRequestStatus = (val: BillingRequestStatus) => {
    setRequestStatus(val);
  };
	const onClickToNavigate = () => {
		if(checkGrant(menuId, 'W')){
    	navigate(PATHS.transaction.billing.charge);
		}
		else{
			showAlert(t('common.nopermission'));
		}
  };

	const onRequestDownloadExcel = (
		selectedMode: DownloadSelectedMode,
		userEmail?: string
	) => {
		if(selectedMode === DownloadSelectedMode.EMAIL
			&& !!userEmail
		){
			let params: BillingExcelParams = {
				email: userEmail,
				mid: mid,
				searchType: searchType,
				startDate: startDate,
				endDate: endDate,
				requestStatus: requestStatus,
				processResult: processResult,
				paymentMethod: paymentMethod
			};
			billingExcel(params).then((rs) => {
				console.log(rs);
				snackBar('이메일로 엑셀파일 요청이 완료되었습니다.');
			}).catch((e: any) => {
				if(e.response?.data?.error?.message){
					snackBar(e.response?.data?.error?.message);
					return;
				}
			});
		}
  };

	const setDetailData = (detailData: DetailData) => {
		setDetailOn(detailData.detailOn);
		setDetailTid(detailData.tid);
	};

	const checkUsedFilter = () => {
    let rs: boolean = true;
    if(searchType === defaultParams.searchType
      && searchKeyword === defaultParams.searchKeyword
      && startDate === defaultParams.startDate
      && endDate === defaultParams.endDate
      && requestStatus === defaultParams.requestStatus
      && processResult === defaultParams.processResult
      && paymentMethod === defaultParams.paymentMethod
      && minAmount === defaultParams.minAmount
      && maxAmount === defaultParams.maxAmount
    ){
      rs =  false;
    }
    setFilterUsed(rs);
	};

  useEffect(() => {
		callList();
		checkUsedFilter();
	}, [
		mid, searchType, searchKeyword,
		startDate, endDate, sortType,
		requestStatus, processResult, paymentMethod,
		minAmount, maxAmount
	]);
	
	return (
		<>
			<main>
				<div className="tab-content pb-86">
					<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={ t('transaction.searchOptions') }
											onClick={ onClickToOpenFilter }
										/>
										{ filterUsed &&
                      <span className="notification-badge2"></span>
                    }
									</button>
								</div>
								<button className="download-btn">
									<img
										src={ IMAGE_ROOT + '/ico_download.svg' }
										alt={ t('transaction.download') }
										onClick={ onClickToOpenDownloadBottomSheet }
									/>
								</button>
							</div>
						</div>
							
						<div className="filter-section">
							<SortTypeBox
								sortType={ sortType }
								onClickToSort={ onClickToSort }
							></SortTypeBox>
							<div className="excrow">
								<div className="full-menu-keywords no-padding">
								{
									getBillingRequestStatusBtnGroup(t).map((value: any, index: number) => (
										<span
											key={ `key-service-code=${ index }` }
											className={ `keyword-tag ${(requestStatus === value.value)? 'active': ''}` }
											onClick={ () => onClickToRequestStatus(value.value) }
										>{ value.name }</span>
									))
								}
								</div>
							</div>
						</div>
						<BillingList 
							listItems={ listItems }
							transactionCategory={ TransactionCategory.Billing }
							setDetailData={ setDetailData }
							filterUsed={ filterUsed }
							onClickToOpenFilter={ onClickToOpenFilter }
              onClickToOpenDownloadBottomSheet={ onClickToOpenDownloadBottomSheet }
						></BillingList>
						<div ref={ setTarget }></div>
					</div>
				</div>
			</main>
			<div className="apply-row">
        <button
          className="btn-50 btn-blue flex-1"
          onClick={ () => onClickToNavigate() }
        >{ t('transaction.list.paymentRequest') }</button>
      </div>
			<BillingFilter
        filterOn={ filterOn }
        setFilterOn={ setFilterOn }
				mid={ mid }
				searchType={ searchType }
				searchKeyword={searchKeyword }
				startDate={ startDate }
				endDate={ endDate }
				requestStatus={ requestStatus }
				processResult={ processResult }
				paymentMethod={ paymentMethod }
				minAmount={ minAmount }
				maxAmount={ maxAmount }
				setMid={ setMid }
				setSearchType={ setSearchType }
				setSearchKeyword={ setSearchKeyword }
				setStartDate={ setStartDate }
				setEndDate={ setEndDate }
				setRequestStatus={ setRequestStatus }
				setProcessResult={ setProcessResult }
				setPaymentMethod={ setPaymentMethod }
				setMinAmount={ setMinAmount }
				setMaxAmount={ setMaxAmount }
      ></BillingFilter>
			<BillingDetail
				detailOn={ detailOn }
				setDetailOn={ setDetailOn }
				tid={ detailTid }
			></BillingDetail>
			{ !!downloadBottomSheetOn &&
				<DownloadBottomSheet
					bottomSheetOn={ downloadBottomSheetOn }
					setBottomSheetOn={ setDownloadBottomSheetOn }
					imageMode={ false }
					emailMode={ true }
					sendRequest={ onRequestDownloadExcel }
				></DownloadBottomSheet>
			}
		</>
	);
};