import React, { Fragment } from 'react';
import { queryDataFormater, enumToOption, usePagination, useSelect, Toast, useRadioButton } from '@janda-com/front';
import { useQuery } from '@apollo/client';
import { history, historyVariables, SmsType, myManager, HistoryItemType } from '../../types/api';
import { GET_HISTORY, GET_SMS_MANAGER } from '../../apollo/queries';
import client from '../../apollo/apolloClient';
import { DEFAULT_HISTORY } from '../../types/defaults';
import SmsHistory from './SmsHistory';
import { IPageInfo } from '../../types/interface';
import { lang as LANG } from '../../lang/langFn';
import { ISmsConfig } from '../../app';


export interface ISmsHistoryProp {
	onChargeClick: () => void
}

interface Iprops extends ISmsHistoryProp {
	config: ISmsConfig
}


const historyTypeOp = [
	{
		label: '사용내역',
		value: HistoryItemType.USAGE
	},
	{
		label: '충전내역',
		value: HistoryItemType.CHARGE
	}
];


// TODO 이것 완성
const SmsHistoryWrap: React.FC<Iprops> = ({ onChargeClick }) => {
	const paginationHook = usePagination(1);
	const options = enumToOption(LANG, "SmsType", SmsType);
	const filterHook = useSelect<SmsType>(options[0] as any, options);
	const historyTypeRadioHook = useRadioButton([historyTypeOp[0].value], historyTypeOp)

	const { data: managerData } = useQuery<myManager>(GET_SMS_MANAGER, {
		client,
		onError: e => {
			console.error(e);
		},
	});

	const manager = queryDataFormater(managerData, 'MyManager', 'data', undefined) || undefined;

	const { data, loading } = useQuery<history, historyVariables>(GET_HISTORY, {
		client,
		variables: {
			filter: {
				historyType: historyTypeRadioHook.selectedValues[0] as HistoryItemType,
				smsType: filterHook.selectedOption?.value,
			},
			pageArgs: {
				page: paginationHook.page,
				row: 20,
				sort: 'createdAt'
			},
		}
	});

	const historyData = queryDataFormater(data, 'History', 'data', undefined) || undefined;

	const { currentPage, items, rowCount, totalPage } = historyData || DEFAULT_HISTORY;

	const pageInfo: IPageInfo = {
		currentPage,
		rowCount,
		totalPage
	};

	if (loading) {
		return <div>

		</div>
	}
	if (!manager) return <div />

	return (
		<Fragment>
			<SmsHistory historyTypeRadioHook={historyTypeRadioHook} onChargeClick={onChargeClick} manager={manager} filterHook={filterHook} paginationHook={paginationHook} pageInfo={pageInfo} historyItems={items} loading={loading} />
			<Toast />
		</Fragment>
	);
};

export default SmsHistoryWrap;
