import { styled } from 'styled-components';
import { useEffect, useState } from 'react';

import { Title } from '../../styles/Components';
import { TextInput, BtnWrapper } from '../../styles/Components';
import Button from '../../components/common/button/Button';
import Modal from '../../components/common/modal/Modal';
import { UserChangeNickName } from '../../apis';
import { alertTypes } from '../../assets/data/types';
import { useAlert } from '../../context/AlertProvider';
import { useLoading } from '../../context/LoadingProvider';

const NicknameChangeModal = ({ pwPop, handleClick, dataList }) => {
	const {showModal, showToast} = useAlert();
	const {withLoading} = useLoading();

	let nickName = dataList.char_info && dataList.char_info.character_name;

	const [resultData, setResultData] = useState({
		guid: '',
		nickname: '',
		new_nickname: '',
	});

	useEffect(() => {
		setResultData({ ...resultData,
			guid: dataList.user_info && dataList.user_info.aid,
			nickname: dataList.char_info && dataList.char_info.character_name
		});
	}, [dataList]);

	const handleSubmit = async (type, param = null) => {
		switch (type) {

			case "nicknameChangeSubmit":
				showModal('NICKNAME_CHANGES_CONFIRM', {
					type: alertTypes.confirm,
					onConfirm: () => handleSubmit('nicknameChange')
				});
				break;

			case "nicknameChange":
				const token = sessionStorage.getItem('token');

				await withLoading(async () => {
					return await UserChangeNickName(token, resultData);
				}).then(data =>{
					console.log(data);
					if(data.result === 'ERROR'){
						showToast(data.data.message, {type: alertTypes.error});
					}else{
						showToast('NICKNAME_CHANGES_COMPLETE', {type: alertTypes.success});
					}
				}).catch(error => {
					showToast(error, {type: alertTypes.error});
				}).finally(() => {
					handleClick();
				});
				break;
		}
	}

	return (
		<>
			<Modal $view={pwPop} min="480px">
				<Title $align="center">닉네임 변경</Title>
				<PwSetTable>
					<colgroup>
						<col width="120" />
						<col />
					</colgroup>
					<tbody>
						<tr>
							<th>기존 닉네임</th>
							<td>{nickName}</td>
						</tr>
						<tr>
							<th>변경 닉네임</th>
							<td>
								<TextInput placeholder="닉네임을 입력하세요." onChange={e => setResultData({ ...resultData, new_nickname: e.target.value })} maxLength={12} />
								<ChangeNotice>* 최대 12글자까지 가능합니다.</ChangeNotice>
							</td>
						</tr>
					</tbody>
				</PwSetTable>
				<BtnWrapper $justify="center" $gap="10px">
					<Button theme="line" text="취소" handleClick={handleClick} />
					<Button theme="primary" text="변경하기" handleClick={() => handleSubmit('nicknameChangeSubmit')} />
				</BtnWrapper>
			</Modal>
		</>
	);
};

export default NicknameChangeModal;
const PwSetTable = styled.table`
	width: 400px;
	margin: 30px 0;
	th,
	td {
		padding: 10px 0;
	}
`;
const ChangeNotice = styled.span`
	font-size: 12px;
	font-weight: 300;
	color: ${props => props.$color || '#999'};
	margin-top: 10px;
	display: block;
`;