import React, { Fragment, useState } from 'react';

import { Title, FormWrapper, InputItem, TextInput } from '../../styles/Components';
import { CommonSearchBar, useCommonSearch } from '../../components/ServiceManage';
import { ItemDeleteAPI } from '../../apis';

import { authType } from '../../assets/data';
import { CaliTable, TableHeader } from '../../components/common';
import tableInfo from '../../assets/data/pages/itemTable.json';
import { useModal, useTable, withAuth } from '../../hooks/hook';
import { alertTypes } from '../../assets/data/types';
import { useAlert } from '../../context/AlertProvider';
import { useLoading } from '../../context/LoadingProvider';
import useEnhancedCommonSearch from '../../hooks/useEnhancedCommonSearch';
import CustomConfirmModal from '../../components/common/modal/CustomConfirmModal';
import { useTranslation } from 'react-i18next';

const Items = () => {
	const token = sessionStorage.getItem('token');
	const {showModal, showToast} = useAlert();
	const {withLoading} = useLoading();
	const { t } = useTranslation();

	const [itemCount, setItemCount] = useState('1');
	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		delete: 'hidden',
	});


	const {
		config,
		searchParams,
		data: dataList,
		handleSearch,
		handleReset,
		updateSearchParams,
		loading,
		configLoaded,
		paginationType,
		pagination,
		goToNextPage,
		goToPrevPage,
	} = useEnhancedCommonSearch("itemSearch");

	const {
		selectedRows,
		handleSelectRow,
		isRowSelected
	} = useTable(dataList?.list || [], {mode: 'single'});

	const handleAction = async (action, item = null) => {
		switch (action) {
			case "delete":
				handleModalView('delete');
				break;
			case 'deleteCountConfirm':
				showModal('ITEM_DELETE_CONFIRM', {
					type: alertTypes.confirm,
					onConfirm: () => handleAction('deleteConfirm')
				});
				break;
			case "deleteConfirm":
				handleModalClose('delete');
				const selectRow = selectedRows[0];
				let params = {};
				params.user_guid = selectRow.user_guid;
				params.item_guid = selectRow.item_guid;
				params.item_count = selectRow.count;
				params.delete_count = itemCount;

				await withLoading(async () => {
					return await ItemDeleteAPI(token, params);
				}).then(data => {
					if(data.result === "SUCCESS") {
						showToast('DEL_COMPLETE', {type: alertTypes.success});
					}else{
						showToast('DELETE_FAIL', {type: alertTypes.error});
					}
				}).catch(reason => {
					showToast('API_FAIL', {type: alertTypes.error});
				}).finally(() => {
					setItemCount('1');
					handleSearch(updateSearchParams);
				});

				break;

			case "restore":
				showModal('ITEM_RESTORE_CONFIRM', {
					type: alertTypes.confirm,
					onConfirm: () => handleAction('restoreConfirm')
				});
				break;
			case "restoreConfirm":
				let list = [];

				selectedRows.map(data => {
					list.push({
						id: data.id,
					});
				});

				await withLoading(async () => {
					return await ItemDeleteAPI(token, list);
				}).then(data => {
					if(data.result === "SUCCESS") {
						showToast('ITEM_RESTORE_COMPLETE', {type: alertTypes.success});
					}else if(data.result === "ERROR_AUCTION_STATUS_IMPOSSIBLE"){
						showToast('LAND_AUCTION_ERROR_DELETE_STATUS', {type: alertTypes.error});
					}else{
						showToast('DELETE_FAIL', {type: alertTypes.error});
					}
				}).catch(reason => {
					showToast('API_FAIL', {type: alertTypes.error});
				}).finally(() => {
					handleSearch(updateSearchParams);
				});

				break;

			default:
				break;
		}
	};

	const handleItemCount = e => {
		const selectRowCount = selectedRows[0]?.count;
		if (e.target.value === '0' || e.target.value === '-0') {
			setItemCount('1');
			e.target.value = '1';
		} else if (e.target.value < 0) {
			let plusNum = Math.abs(e.target.value);
			setItemCount(plusNum);
		} else if(e.target.value > selectRowCount){
			showToast('DEL_COUNT_CHECK',{type:alertTypes.warning});
			setItemCount(selectRowCount);
		} else {
			setItemCount(e.target.value);
		}
	};

	const ConfirmChild = () => {
		if(selectedRows === undefined || selectedRows.length === 0) return;
		const selectRow = selectedRows[0];
		return(
			<InputItem>
				<p>{t('DEL_COUNT_CONFIRM', {count: selectRow?.count})}</p>
				<TextInput placeholder="수량" type="number" value={itemCount} onChange={e => handleItemCount(e)} width="200px" />
			</InputItem>
		);
	}

	return (
		<>
			<Title>아이템 관리</Title>
			<FormWrapper>
				<CommonSearchBar
					config={config}
					searchParams={searchParams}
					onSearch={(newParams, executeSearch = true) => {
						if (executeSearch) {
							handleSearch(newParams);
						} else {
							updateSearchParams(newParams);
						}
					}}
					onReset={handleReset}
				/>
			</FormWrapper>

			{/* 조회헤더 */}
			<TableHeader
				config={tableInfo.header}
				selectedRows={selectedRows}
				onAction={handleAction}
				pagination={pagination}
				goToNextPage={goToNextPage}
				goToPrevPage={goToPrevPage}
			/>

			{/* 조회테이블 */}
			<CaliTable
				columns={tableInfo.columns}
				data={dataList?.list}
				onSelectRow={handleSelectRow}
				isRowSelected={isRowSelected}
				onAction={handleAction}
				loading={loading}
			/>

			<CustomConfirmModal
				ChildView={ConfirmChild}
				view={modalState.deleteModal}
				handleSubmit={() => handleAction('deleteCountConfirm')}
				handleCancel={() => handleModalClose('delete')}
				handleClose={() => handleModalClose('delete')}
			/>
		</>
	);
};

export default withAuth(authType.itemRead)(Items);
