import moment from 'moment';
import { IMAGE_ROOT } from "@/shared/constants/common";
import { useState, useEffect } from "react";
import { LinkPaymentHistoryFilter } from "./filter/link-payment-history-filter";
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { PATHS } from "@/shared/constants/paths";
import { LinkPaymentHistoryList } from "./link-payment-history-list";
import { SortTypeBox } from '@/entities/common/ui/sort-type-box';
import { DefaultRequestPagination, SortTypeKeys } from '@/entities/common/model/types';
import { AdditionalServiceCategory, ProcessResult } from "../../model/types";
import { useExtensionLinkPayHistoryListMutation } from '../../api/link-payment/use-extension-link-pay-history-list-mutation';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { useExtensionLinkPayHistoryDownloadExcelMutation } from '../../api/link-payment/use-extension-link-pay-history-download-excel-mutation';
import { useStore } from '@/shared/model/store';
import { ExtensionLinkPayHistoryListParams, LinkPaymentHistoryListItem, LinkPaymentPaymentMethod, LinkPaymentPaymentStatus, LinkPaymentSearchCl, LinkPaymentSendMethod, LinkPaymentSendStatus } from '../../model/link-pay/types';
import { EmailBottomSheet } from '@/entities/common/ui/email-bottom-sheet';

const paymentResultBtnGroup = [
	{ name: '전체', value: LinkPaymentPaymentStatus.ALL },
	{ name: '미완료/활성화', value: LinkPaymentPaymentStatus.ACTIVATE },
	{ name: '입금요청', value: LinkPaymentPaymentStatus.DEPOSIT_REQUEST },
	{ name: '결제완료', value: LinkPaymentPaymentStatus.PAYMENT_COMPLETE },
	{ name: '결제실패', value: LinkPaymentPaymentStatus.PAYMENT_FAIL },
	{ name: '결제중단/비활성화', value: LinkPaymentPaymentStatus.INACTIVE },
];

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

	const [filterOn, setFilterOn] = useState<boolean>(false);
	const [sortType, setSortType] = useState<SortTypeKeys>(SortTypeKeys.LATEST);
	const [listItems, setListItems] = useState<Array<LinkPaymentHistoryListItem>>([]);
	const [pageParam, setPageParam] = useState<DefaultRequestPagination>(DEFAULT_PAGE_PARAM);

	const [mid, setMid] = useState<string>(userMid);
	const [searchCl, setSearchCl] = useState<LinkPaymentSearchCl>(LinkPaymentSearchCl.PHONE);
	const [searchValue, setSearchValue] = useState<string>('');
	const [paymentMethod, setPaymentMethod] = useState<LinkPaymentPaymentMethod>(LinkPaymentPaymentMethod.CARD);
	const [fromDate, setFromDate] = useState(moment().format('YYYYMMDD'));
	const [toDate, setToDate] = useState(moment().format('YYYYMMDD'));
	const [paymentStatus, setPaymentStatus] = useState<LinkPaymentPaymentStatus>(LinkPaymentPaymentStatus.ALL);
	const [sendStatus, setSendStatus] = useState<LinkPaymentSendStatus>(LinkPaymentSendStatus.ALL);
	const [sendMethod, setSendMethod] = useState<LinkPaymentSendMethod>(LinkPaymentSendMethod.ALL);
	const [emailBottomSheetOn, setEmailBottomSheetOn] = useState<boolean>(false);

	const { mutateAsync: linkPayHistoryList } = useExtensionLinkPayHistoryListMutation();
	const { mutateAsync: downloadExcel } = useExtensionLinkPayHistoryDownloadExcelMutation();

	const onClickToNavigate = () => {
		navigate(PATHS.additionalService.linkPayment.request)
	};

	const callList = (option?: {
		sortType?: SortTypeKeys,
		status?: LinkPaymentPaymentStatus
	}) => {
		let listParams: ExtensionLinkPayHistoryListParams = {
			mid: mid,
			searchCl: searchCl,
			searchValue: searchValue,
			fromDate: fromDate,
			toDate: toDate,
			paymentStatus: option?.status ?? paymentStatus,
			sendStatus: sendStatus,
			sendMethod: sendMethod,
			page: pageParam
		};

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

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

	const onClickToOpenEmailBottomSheet = () => {
		setEmailBottomSheetOn(true);
	};

	const onSendRequest = (selectedEmail?: string) => {
		if (selectedEmail) {
			downloadExcel({
				mid: mid,
				email: selectedEmail,
				searchCl: searchCl,
				searchValue: searchValue,
				paymentMethod: paymentMethod,
				fromDate: fromDate,
				toDate: toDate,
				paymentStatus: paymentStatus,
				sendStatus: sendStatus,
				sendMethod: sendMethod,
			}).then((rs) => {
				console.log('Excel Download Status: ' + rs.status);
			});
		}
		setEmailBottomSheetOn(false);
	};

	const onClickPaymentStatus = (val: LinkPaymentPaymentStatus) => {
		setPaymentStatus(val);
	}

	const onClickToSort = (sort: SortTypeKeys) => {
		setSortType(sort);
		callList({
			sortType: sort
		});
	};

	const onClickToOpenFilter = () => {
		setFilterOn(!filterOn);
	};

	useEffect(() => {
		callList();
	}, [
		mid,
		searchCl,
		searchValue,
		paymentMethod,
		fromDate,
		toDate,
		paymentStatus,
		sendStatus,
		sendMethod
	]);

	return (
		<>
			<section className="summary-section pt-30">
				<div className="credit-controls">
					<div>
						<input
							className="credit-period"
							type="text"
							value={moment(fromDate).format('YYYY.MM.DD') + '-' + moment(toDate).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"
						aria-label="다운로드"
						onClick={() => onClickToOpenEmailBottomSheet()}
					>
						<img
							src={IMAGE_ROOT + '/ico_download.svg'}
							alt="다운로드"
						/>
					</button>
				</div>
			</section>

			<div className="filter-section">
				<SortTypeBox
					sortType={sortType}
					onClickToSort={onClickToSort}
				>
				</SortTypeBox>
				<div className="excrow">
					<div className="full-menu-keywords no-padding">
						{
							paymentResultBtnGroup.map((value, index) => (
								<span
									key={`key-service-code=${index}`}
									className={`keyword-tag ${(paymentStatus === value.value) ? 'active' : ''}`}
									onClick={() => onClickPaymentStatus(value.value)}
								>{value.name}</span>
							))
						}
					</div>
				</div>
			</div>

			<LinkPaymentHistoryList
				listItems={listItems}
				additionalServiceCategory={AdditionalServiceCategory.LinkPaymentHistory}
				mid={mid}
			></LinkPaymentHistoryList>
			<div className="apply-row">
				<button
					className="btn-50 btn-blue flex-1"
					onClick={() => onClickToNavigate()}
				>결제 신청</button>
			</div>
			<LinkPaymentHistoryFilter
				filterOn={filterOn}
				setFilterOn={setFilterOn}
				mid={mid}
				searchCl={searchCl}
				searchValue={searchValue}
				fromDate={fromDate}
				toDate={toDate}
				paymentStatus={paymentStatus}
				sendStatus={sendStatus}
				sendMethod={sendMethod}
				setMid={setMid}
				setSearchType={setSearchCl}
				setSearchKeyword={setSearchValue}
				setStartDate={setFromDate}
				setEndDate={setToDate}
				setPaymentStatus={setPaymentStatus}
				setSendStatus={setSendStatus}
				setSendMethod={setSendMethod}
			></LinkPaymentHistoryFilter>
			<EmailBottomSheet
				bottomSheetOn={emailBottomSheetOn}
				setBottomSheetOn={setEmailBottomSheetOn}
				imageSave={false}
				sendEmail={true}
				sendRequest={onSendRequest}
			></EmailBottomSheet>
		</>
	);
}