import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

import styled from 'styled-components';
import Profile from '../../assets/img/datamanage/img-profile.png';
import NicknameChangeModal from '../../components/DataManage/NicknameChangeModal';
import EditIcon from '../../assets/img/icon/icon-edit.png';
import { UserChangeAdminLevel, UserInfoView, UserKick } from '../../apis/Users';
import { SelectInput } from '../../styles/Components';
import { adminLevelType, authType, modalTypes } from '../../assets/data';
import DynamicModal from '../common/modal/DynamicModal';
import { useTranslation } from 'react-i18next';
import { useRecoilValue } from 'recoil';
import { authList } from '../../store/authList';
import { convertKTC } from '../../utils';
import { EditButton, ProfileWrapper, UserDefault, UserInfoTable } from '../../styles/ModuleComponents';
import { TableSkeleton } from '../Skeleton/TableSkeleton';
import { UserInfoSkeleton } from '../Skeleton/UserInfoSkeleton';
import { opUserSessionType } from '../../assets/data/options';
import Button from '../common/button/Button';
import { useModal } from '../../hooks/hook';
import { InitData } from '../../apis/Data';
import { useAlert } from '../../context/AlertProvider';
import { useLoading } from '../../context/LoadingProvider';
import { alertTypes } from '../../assets/data/types';

const UserDefaultInfo = ({ userInfo }) => {
	const { t } = useTranslation();
	const authInfo = useRecoilValue(authList);
	const token = sessionStorage.getItem('token');
	const {showModal, showToast} = useAlert();
	const {withLoading} = useLoading();

	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		pwChange: 'hidden'
	});
	const [dataList, setDataList] = useState({});
	const [loading, setLoading] = useState(true);
	const [authDelete, setAuthDelete] = useState(false);

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

	useEffect(() => {
		if(userInfo && Object.keys(userInfo).length > 0) {
			fetchData();
		}
	}, [userInfo]);

	const fetchData = async () => {
		setLoading(true);
		await UserInfoView(token, userInfo.guid).then(data => {
			setDataList(data);
			setLoading(false);
		});
	};

	const handleSubmit = async (type, param = null) => {
		let params = {};

		switch (type) {
			case "gmLevelChangeSubmit":
				showModal('USER_GM_CHANGE', {
					type: alertTypes.confirm,
					onConfirm: () => handleSubmit('gmLevelChange', param)
				});
				break;

			case "userKickSubmit":
				showModal('USER_KICK_CONFIRM', {
					type: alertTypes.confirm,
					onConfirm: () => handleSubmit('userKick')
				});
				break;

			case "gmLevelChange":
				params.guid = userInfo.guid;
				params.admin_level = param;

				await withLoading(async () => {
					return await UserChangeAdminLevel(token, params);
				}).then(data =>{
					showToast('USER_GM_CHANGE_COMPLETE', {type: alertTypes.success});
				}).catch(error => {
					showToast(error, {type: alertTypes.error});
				}).finally(() => {
					fetchData();
				});
				break;

			case "userKick":
				params.guid = userInfo.guid;
				await withLoading(async () => {
					return await UserKick(token, params);
				}).then((data) =>{
					showToast('USER_KICK_COMPLETE', {type: alertTypes.success});
				}).catch(error => {
					showToast(error, {type: alertTypes.error});
				}).finally(() => {
					fetchData();
				});
				break;
		}
	}

	return (
		loading ? <UserInfoSkeleton /> :
		<>
			<div>
				<UserDefault>
					<ProfileWrapper>
						<img src={Profile} alt="" />
					</ProfileWrapper>
					<UserInfoTable $maxwidth="530px">
						<tbody>
							<tr>
								<th>GUID</th>
								<td>{dataList.user_info && dataList.user_info.aid}</td>
							</tr>
							<tr>
								<th>Account ID</th>
								<td>{dataList.user_info && dataList.user_info.user_id}</td>
							</tr>
							<tr>
								<th>국가</th>
								<td>{dataList.user_info && dataList.user_info.nation}</td>
							</tr>
							<tr>
								<th>접속상태</th>
								<StatusCell>{dataList.user_session !== undefined && opUserSessionType.find(session => session.value === dataList.user_session)?.name}
									{<Button
										theme={(dataList.user_session && authDelete) ? "line" : "disable"}
										id={"user_session"}
										name="kick"
										text="KICK"
										handleClick={() => handleSubmit('userKickSubmit')}
										disabled={(!authDelete || !dataList.user_session)}
									/>}
								</StatusCell>
							</tr>
							<tr>
								<th>계정 생성일</th>
								<td>
									{dataList.user_info && convertKTC(dataList.user_info.create_dt)}
								</td>
							</tr>
							<tr>
								<th>최근 접속일자</th>
								<td>{dataList.user_info && convertKTC(dataList.user_info.access_dt)}</td>
							</tr>
							<tr>
								<th>최근 종료일자</th>
								<td>{dataList.user_info && convertKTC(dataList.user_info.end_dt)}</td>
							</tr>
							<tr>
								<th>전자지갑 URL</th>
								<td>
									<Link>{dataList.user_info && dataList.user_info.wallet_url}</Link>
								</td>
							</tr>
							<tr>
								<th>GM권한</th>
								<td>
									<SelectInput value={dataList?.user_info?.admin_level}
												 onChange={e => handleSubmit('gmLevelChangeSubmit', e.target.value)}
												 disabled={authInfo.auth_list && !authInfo.auth_list.some(auth => auth.id === authType.userSearchUpdate)} >
										{adminLevelType.map((data, index) => (
											<option key={index} value={data.value}>
												{data.name}
											</option>
										))}
									</SelectInput>
								</td>
							</tr>
						</tbody>
					</UserInfoTable>
				</UserDefault>
				<UserInfoTable $maxwidth="720px">
					<colgroup>
						<col />
						<col />
						<col width="120" />
						<col />
					</colgroup>
					<tbody>
						<tr>
							<th>캐릭터 아바타명</th>
							<td colSpan="3">
								{dataList.char_info && dataList.char_info.character_name}
								<EditButton
									hidden={true}
									onClick={e => {
										e.preventDefault();
										handleModalClose('pwChange');
									}}></EditButton>
							</td>
						</tr>
						<tr>
							<th>시즌 패스 레벨</th>
							<td colSpan="3">{dataList.char_info && dataList.char_info.level}</td>
						</tr>
						<tr>
							<th>골드</th>
							<td>{dataList.char_info && dataList.char_info.gold_cali}</td>
							<th>사파이어</th>
							<td>{dataList.char_info && dataList.char_info.blue_cali}</td>
						</tr>
						<tr>
							<th>칼리움</th>
							<td>{dataList.char_info && dataList.char_info.red_cali}</td>
							<th>루비</th>
							<td>{dataList.char_info && dataList.char_info.black_cali}</td>
						</tr>
					</tbody>
				</UserInfoTable>
			</div>
			<NicknameChangeModal pwPop={modalState.pwChangeModal} handleClick={() => handleModalClose('pwChange')} dataList={dataList} />
		</>
	);
};
export default UserDefaultInfo;

const StatusCell = styled.td`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
`;