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 { BillingList } from '@/entities/transaction/ui/billing-list';
import { BillingListItem, TransactionCategory, SortByKeys, BillingRequestStatus, BillingProcessResult, BillingPaymentMethod, BillingSearchType } from '@/entities/transaction/model/types';
import { useBillingListMutation } from '@/entities/transaction/api/use-billing-list-mutation';
import { useDownloadExcelMutation } from '@/entities/transaction/api/use-download-excel-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constants';
import { BillingFilter } from '@/entities/transaction/ui/filter/billing-filter';
import { SortOptionsBox } from '@/entities/transaction/ui/sort-options-box';
import { BillingRequestStatusBtnGroup } from '@/entities/transaction/model/contant';
import { HeaderType } from '@/entities/common/model/types';
import { 
	useSetOnBack,
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';

export const BillingListPage = () => {
	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<BillingSearchType>(BillingSearchType.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 [requestStatus, setRequestStatus] = useState<BillingRequestStatus>(BillingRequestStatus.ALL);
	const [processResult, setProcessResult] = useState<BillingProcessResult>(BillingProcessResult.ALL);
	const [paymentMethod, setPaymentMethod] = useState<BillingPaymentMethod>(BillingPaymentMethod.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: billingList } = useBillingListMutation();
	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: searchType,
			searchKeyword: searchKeyword,
      startDate: startDate,
      endDate: endDate,
      requestStatus: requestStatus,
      processResult: processResult,
      paymentMethod: paymentMethod,
			minAmount: newMinAmount,
			maxAmount: newMaxAmount,
			pagination: pageParam
    };    
    
    billingList(listParams).then((rs) => {
      setListItems(assembleData(rs.content));
    });
	}

	const assembleData = (content: Array<BillingListItem>) => {
		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 onClickToRequestStatus = (val: BillingRequestStatus) => {
    setRequestStatus(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">
								{
									BillingRequestStatusBtnGroup.map((value, index) => (
										<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 }
						></BillingList> 
					</div>
				</div>
			</main>
			<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>
		</>
	);
};