import styled from 'styled-components';
import { useState, useEffect } from 'react';
import { UserInventoryItemDelete, UserInventoryView } from '../../apis/Users';
import Button from '../common/button/Button';
import ConfirmModal from '../common/modal/ConfirmModal';
import CompletedModal from '../common/modal/CompletedModal';
import { useTranslation } from 'react-i18next';
import { InputItem, SelectInput, TextInput } from '../../styles/Components';
import CustomConfirmModal from '../common/modal/CustomConfirmModal';
import { ivenTabType } from '../../assets/data';
import { useRecoilValue } from 'recoil';
import { authList } from '../../store/authList';
import { TableSkeleton } from '../Skeleton/TableSkeleton';
import { InfoSubTitle, UserDefaultTable, UserTableWrapper } from '../../styles/ModuleComponents';

const UserInventoryInfo = ({ userInfo }) => {
	const { t } = useTranslation();
	const authInfo = useRecoilValue(authList);

	const [dataList, setDataList] = useState();
	const [itemCount, setItemCount] = useState('');
	const [selected, setSelected] = useState({});
	const [itemUpdateCount, setItemUpdateCount] = useState('1');
	const [deleteConfirmModal, setDeleteConfirmModal] = useState('hidden');
	const [deleteSubmitModal, setDeleteSubmitModal] = useState('hidden');
	const [deleteCompleteModal, setDeleteCompleteModal] = useState('hidden');
	const [authDelete, setAuthDelete] = useState(false);
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		fetchData();
	}, []);

	useEffect(() => {
		setAuthDelete(authInfo.auth_list.some(auth => auth.id === 35));
	}, [authInfo]);

	const fetchData = async () => {
		const token = sessionStorage.getItem('token');
		await UserInventoryView(token, userInfo.guid).then(data => {
			setDataList(data);
			setLoading(false);
		});
	};

	const handleDeleteConfirmModal = (data, type) =>{
		setItemCount(data.count);
		let row;
		switch(type){
			case ivenTabType.CLOTH:
				row = dataList.inventory_list.cloth.find(item => item.item_guid === data.item_guid);
				row.type = ivenTabType.CLOTH;
				break;
			case ivenTabType.PROP:
				row = dataList.inventory_list.prop.find(item => item.item_guid === data.item_guid);
				row.type = ivenTabType.PROP;
				break;
			case ivenTabType.BEAUTY:
				row = dataList.inventory_list.beauty.find(item => item.item_guid === data.item_guid);
				row.type = ivenTabType.BEAUTY;
				break;
			case ivenTabType.TATTOO:
				row = dataList.inventory_list.tattoo.find(item => item.item_guid === data.item_guid);
				row.type = ivenTabType.TATTOO;
				break;
			case ivenTabType.CURRENCY:
				row = dataList.inventory_list.currency.find(item => item.item_guid === data.item_guid);
				row.type = ivenTabType.CURRENCY;
				break;
			default:
				row = dataList.inventory_list.etc.find(item => item.item_guid === data.item_guid);
				row.type = ivenTabType.ETC;
				break;
		}
		setSelected(row);
		setDeleteConfirmModal('view');
	}

	// 개수 입력 모달 hidden
	const handleDeleteConfirmClose = () => {
		setDeleteConfirmModal('hidden');
		setItemUpdateCount(1);
		setSelected({});
	}

	// 삭제 모달 hidden
	const handleDeleteClose = () => {
		setDeleteSubmitModal('hidden');
	}

	const handleDeleteConfirm = () => {
		setDeleteSubmitModal('view');
	}

	// 삭제 처리
	const handleDeleteSubmit = async () => {
		let params = {}
		params.guid = userInfo.guid;
		params.item_guid = selected.item_guid;
		params.current_cnt = selected.count;
		params.cnt = itemUpdateCount;
		const token = sessionStorage.getItem('token');
		const result = await UserInventoryItemDelete(token, params);
		if(result.result === "SUCCESS"){
			//성공시 아이템 삭제 or 개수 차감
			if(selected.count <= itemUpdateCount){
				switch (selected.type) {
					case ivenTabType.CLOTH:
						dataList.inventory_list.cloth.splice(dataList.inventory_list.cloth.findIndex(item => item.item_guid === selected.item_guid), 1);
						break;
					case ivenTabType.PROP:
						dataList.inventory_list.prop.splice(dataList.inventory_list.prop.findIndex(item => item.item_guid === selected.item_guid), 1);
						break;
					case ivenTabType.BEAUTY:
						dataList.inventory_list.beauty.splice(dataList.inventory_list.beauty.findIndex(item => item.item_guid === selected.item_guid), 1);
						break;
					case ivenTabType.TATTOO:
						dataList.inventory_list.tattoo.splice(dataList.inventory_list.tattoo.findIndex(item => item.item_guid === selected.item_guid), 1);
						break;
					case ivenTabType.CURRENCY:
						dataList.inventory_list.currency.splice(dataList.inventory_list.currency.findIndex(item => item.item_guid === selected.item_guid), 1);
						break;
					default:
						dataList.inventory_list.etc.splice(dataList.inventory_list.etc.findIndex(item => item.item_guid === selected.item_guid), 1);
						break;
				}
			}else{
				selected.count = selected.count - itemUpdateCount;
			}
		}
		handleDeleteClose();
		handleDeleteConfirmClose();
		setDeleteCompleteModal('view')
	}

	const handleDeleteComplete = () => {
		setDeleteCompleteModal('hidden');
	}

	const handleItemCount = e => {
		if (e.target.value === '0' || e.target.value === '-0') {
			setItemUpdateCount('1');
			e.target.value = '1';
		} else if (e.target.value < 0) {
			let plusNum = Math.abs(e.target.value);
			setItemUpdateCount(plusNum);
		} else if(e.target.value > itemCount){
			alert(t('DEL_COUNT_CHECK'));
			setItemUpdateCount(itemCount);
		} else {
			setItemUpdateCount(e.target.value);
		}
	};

	const ConfirmChild = () => {
		return(
			<InputItem>
				<p>{t('DEL_COUNT_CONFIRM', {count: itemCount})}</p>
				<TextInput placeholder="수량" type="number" value={itemUpdateCount} onChange={e => handleItemCount(e)} width="200px" />
			</InputItem>
		);
	}

	const InvenTable = ({invenList, title, type}) => {
		return (
			<>
				<InfoSubTitle>{title}</InfoSubTitle>
				<UserTableWrapper>
					<UserDefaultTable>
						<thead>
						<tr>
							<th width="80">no.</th>
							<th width="120">ID</th>
							<th width="50%">아이템</th>
							<th width="100">보유개수</th>
							<th width="60">삭제</th>
						</tr>
						</thead>
						<tbody>
							{invenList.map((el, idx) => {
									return (
										<tr key={idx}>
											<td>{idx + 1}</td>
											<td>{el.item_id}</td>
											<td>{el.item_name}</td>
											<td>{el.count}</td>
											<td>
												<Button theme={authDelete ? "line" : "disable"} id={el.item_guid} name="single" text="삭제" handleClick={e => {handleDeleteConfirmModal(el, type)}} disabled={!authDelete}/>
											</td>
										</tr>
									);
								})}
						</tbody>
					</UserDefaultTable>
				</UserTableWrapper>
			</>
		);
	};

	return (
		loading ? <TableSkeleton count={15}/> :
		<>
			{dataList && dataList.inventory_list && <InvenTable title="의상 탭" type={ivenTabType.CLOTH} invenList={dataList.inventory_list.cloth} />}
			{dataList && dataList.inventory_list && <InvenTable title="소품 탭" type={ivenTabType.PROP} invenList={dataList.inventory_list.prop} />}
			{dataList && dataList.inventory_list && <InvenTable title="미용 탭" type={ivenTabType.BEAUTY} invenList={dataList.inventory_list.beauty} />}
			{dataList && dataList.inventory_list && <InvenTable title="타투 탭" type={ivenTabType.TATTOO} invenList={dataList.inventory_list.tattoo} />}
			{dataList && dataList.inventory_list && <InvenTable title="재화 탭" type={ivenTabType.CURRENCY} invenList={dataList.inventory_list.currency} />}
			{dataList && dataList.inventory_list && <InvenTable title="기타 탭" type={ivenTabType.ETC} invenList={dataList.inventory_list.etc} />}
			<CustomConfirmModal
				ChildView={ConfirmChild}
				view={deleteConfirmModal}
				handleSubmit={handleDeleteConfirm}
				handleCancel={handleDeleteConfirmClose}
				handleClose={handleDeleteConfirmClose}
			/>
			<ConfirmModal
				modalText={t('DEL_CONFIRM')}
				view={deleteSubmitModal}
				handleSubmit={handleDeleteSubmit}
				handleCancel={handleDeleteClose}
				handleClose={handleDeleteClose}
			/>
			<CompletedModal
				view={deleteCompleteModal}
				modalText={t('DEL_COMPLETE')}
				handleComplete={handleDeleteComplete}
			/>
			{/* <InfoSubTitle>의상 탭</InfoSubTitle>
			<UserTableWrapper>
				<UserDefaultTable>
					<thead>
						<tr>
							<th width="80">no.</th>
							<th width="120">ID</th>
							<th width="50%">아이템</th>
							<th width="100">보유개수</th>
						</tr>
					</thead>
					<tbody>
						{dataList &&
							dataList.inventory_list.cloth.map((el, idx) => {
								return (
									<tr key={idx}>
										<td>{idx + 1}</td>
										<td>{el.item_id}</td>
										<td>{el.item_name}</td>
										<td>{el.count}</td>
									</tr>
								);
							})}
					</tbody>
				</UserDefaultTable>
			</UserTableWrapper>
			<InfoSubTitle>소품 탭</InfoSubTitle>
			<UserTableWrapper>
				<UserDefaultTable>
					<thead>
						<tr>
							<th width="80">no.</th>
							<th width="120">ID</th>
							<th width="50%">아이템</th>
							<th width="100">보유개수</th>
						</tr>
					</thead>
					<tbody>
						{dataList &&
							dataList.inventory_list.prop.map((el, idx) => {
								return (
									<tr key={idx}>
										<td>{idx + 1}</td>
										<td>{el.item_id}</td>
										<td>{el.item_name}</td>
										<td>{el.count}</td>
									</tr>
								);
							})}
					</tbody>
				</UserDefaultTable>
			</UserTableWrapper>
			<InfoSubTitle>미용 탭</InfoSubTitle>
			<UserTableWrapper>
				<UserDefaultTable>
					<thead>
						<tr>
							<th width="80">no.</th>
							<th width="120">ID</th>
							<th width="50%">아이템</th>
							<th width="100">보유개수</th>
						</tr>
					</thead>
					<tbody>
						{dataList &&
							dataList.inventory_list.beauty.map((el, idx) => {
								return (
									<tr key={idx}>
										<td>{idx + 1}</td>
										<td>{el.item_id}</td>
										<td>{el.item_name}</td>
										<td>{el.count}</td>
									</tr>
								);
							})}
					</tbody>
				</UserDefaultTable>
			</UserTableWrapper>
			<InfoSubTitle>타투 탭</InfoSubTitle>
			<UserTableWrapper>
				<UserDefaultTable>
					<thead>
						<tr>
							<th width="80">no.</th>
							<th width="120">ID</th>
							<th width="50%">아이템</th>
							<th width="100">보유개수</th>
						</tr>
					</thead>
					<tbody>
						{dataList &&
							dataList.inventory_list.tattoo.map((el, idx) => {
								return (
									<tr key={idx}>
										<td>{idx + 1}</td>
										<td>{el.item_id}</td>
										<td>{el.item_name}</td>
										<td>{el.count}</td>
									</tr>
								);
							})}
					</tbody>
				</UserDefaultTable>
			</UserTableWrapper>
			<InfoSubTitle>기타 탭</InfoSubTitle>
			<UserTableWrapper>
				<UserDefaultTable>
					<thead>
						<tr>
							<th width="80">슬롯 no.</th>
							<th width="320">ID</th>
							<th width="50%">아이템</th>
							<th width="100">보유개수</th>
						</tr>
					</thead>
					<tbody>
						{dataList &&
							dataList.inventory_list.etc.map((el, idx) => {
								return (
									<tr key={idx}>
										<td>{idx + 1}</td>
										<td>{el.item_id}</td>
										<td>{el.item_name}</td>
										<td>{el.count}</td>
									</tr>
								);
							})}
					</tbody>
				</UserDefaultTable>
			</UserTableWrapper> */}
		</>
	);
};

export default UserInventoryInfo;

