import moment from 'moment';
import { 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 { CashReceiptList } from '@/entities/transaction/ui/cash-receipt-list';
import { CashReceiptListItem, TransactionCategory, CashReceiptPurposeType, CashReceiptIssueStatus, CashReceiptProcessResult } from '@/entities/transaction/model/types';
import { useCashReceiptListMutation } from '@/entities/transaction/api/use-cash-receipt-list-mutation';
import { useDownloadExcelMutation } from '@/entities/transaction/api/use-download-excel-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { CashReceiptFilter } from '@/entities/transaction/ui/filter/cash-receipt-filter';
import { SortOptionsBox } from '@/entities/common/ui/sort-options-box';
import { SortByKeys, HeaderType } from '@/entities/common/model/types';
import {
	useSetOnBack,
	useSetHeaderTitle,
	useSetHeaderType,
	useSetFooterMode
} from '@/widgets/sub-layout/use-sub-layout';
import { CashReceiptIssueStatusBtnGroup } from '@/entities/transaction/model/contant';
import { useStore } from '@/shared/model/store';

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

	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>(userMid);
	const [startDate, setStartDate] = useState(moment().subtract(1, 'month').format('YYYY-MM-DD'));
	const [endDate, setEndDate] = useState(moment().format('YYYY-MM-DD'));
	const [purposeType, setPurposeType] = useState<CashReceiptPurposeType>(CashReceiptPurposeType.ALL);
	const [issueStatus, setIssueStatus] = useState<CashReceiptIssueStatus>(CashReceiptIssueStatus.ALL);
	const [processResult, setProcessResult] = useState<CashReceiptProcessResult>(CashReceiptProcessResult.ALL);

	useSetHeaderTitle('현금영수증');
	useSetHeaderType(HeaderType.LeftArrow);
	useSetOnBack(() => {
		navigate(PATHS.home);
	});
	useSetFooterMode(false);

	const { mutateAsync: cashReceiptList } = useCashReceiptListMutation();
	const { mutateAsync: downloadExcel } = useDownloadExcelMutation();

	const callList = (option?: {
		sortBy?: string,
		val?: string
	}) => {
		pageParam.sortBy = (option?.sortBy)? option.sortBy: sortBy;
    setPageParam(pageParam);
		let listParams = {
			mid: mid,
			startDate: startDate,
			endDate: endDate,
			purposeType: purposeType,
			issueStatus: issueStatus,
			processResult: processResult,
			pagination: pageParam
		};

		cashReceiptList(listParams).then((rs) => {
			console.log(rs);
			setListItems(assembleData(rs.content));
		});

	};

	const assembleData = (content: Array<CashReceiptListItem>) => {
		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 onClickToIssueStatus = (val: CashReceiptIssueStatus) => {
		setIssueStatus(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 className="credit-summary">
								<div className="row">
									<span className="label">승인</span>
									<strong className="amount22">
										<NumericFormat
											value={ 83745200 }
											thousandSeparator
											displayType="text"
											suffix='원'
										></NumericFormat>
									</strong>
									<span className="count">
										<NumericFormat
											value={ 2745 }
											thousandSeparator
											displayType="text"
											prefix='('
											suffix='건)'
										></NumericFormat>
									</span>
								</div>
								<div className="row">
									<span className="label">취소</span>
									<strong className="amount19">
										<NumericFormat
											value={ 534407 }
											thousandSeparator
											displayType="text"
											suffix='원'
										></NumericFormat>
									</strong>
									<span className="count">
										<NumericFormat
											value={ 32 }
											thousandSeparator
											displayType="text"
											prefix='('
											suffix='건)'
										></NumericFormat>
									</span>
								</div>
							</div>
						</div>

						<div className="filter-section">
							<SortOptionsBox
								sortBy={ sortBy }
								onClickToSort={ onClickToSort }
							></SortOptionsBox>
							<div>
								<div className="full-menu-keywords no-padding">
								{
									CashReceiptIssueStatusBtnGroup.map((value, index) => (
										<span
											key={`key-service-code=${index}`}
											className={`keyword-tag ${(issueStatus === value.value) ? 'active' : ''}`}
											onClick={() => onClickToIssueStatus(value.value)}
										>{value.name}</span>
									))
								}
								</div>
							</div>
						</div>
						<CashReceiptList
							listItems={ listItems }
							transactionCategory={ TransactionCategory.CashReceipt }
						></CashReceiptList>
					</div>
				</div>
			</main>
			<CashReceiptFilter
				filterOn={ filterOn }
				setFilterOn={ setFilterOn }
				mid={ mid }
				startDate={ startDate }
				endDate={ endDate }
				purposeType={ purposeType }
				issueStatus={ issueStatus }
				processResult={ processResult }
				setMid={ setMid }
				setStartDate={ setStartDate }
				setEndDate={ setEndDate }
				setPurposeType={ setPurposeType }
				setIssueStatus={ setIssueStatus }
				setProcessResult={ setProcessResult }
			></CashReceiptFilter>
		</>
	);
};