import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';

import { PasswordValidation } from './PasswordValidation';

import styled from 'styled-components';

import { FormBox, AccountTitle, FormWrapper, BtnWrapper, ModalText } from '../../styles/Components';
import Button from '../../components/common/button/Button';
import Modal from '../../components/common/modal/Modal';
import CloseIcon from '../../assets/img/icon/icon-close.png';

import { AccountEditItem } from '../../components/account';
import { AuthEdit } from '../../apis';

const AccountEdit = () => {
	const [completeModal, setCompleteModal] = useState('hidden');
	const navigate = useNavigate();
	const [confirmText, setConfirmText] = useState('');

	const onSubmitData = async data => {
		const token = sessionStorage.getItem('token');

		const message = await AuthEdit(data, token);
		message.data.data.message !== '수정 하였습니다.' ? setConfirmText(message.data.data.message) : setConfirmText('변경이 완료되었습니다.');

		setForm('');
		handleCompleteModal();
	};

	const {
		register,
		formState: { errors },
		watch,
		handleSubmit,
	} = useForm({
		resolver: yupResolver(PasswordValidation),
		mode: 'onChange',
	});

	const values = watch();

	const [form, setForm] = useState({
		newPassword: '',
		passwordConfirm: '',
	});

	const { newPassword, passwordConfirm } = form;

	const onChange = e => {
		const nextForm = {
			...form,
			[e.target.name]: e.target.value,
		};
		setForm(nextForm);
	};

	// console.log(form);

	const AccountEditData = [
		{
			title: '신규 비밀번호',
			name: 'newPassword',
			placeholder: '영어/숫자/특수문자 조합 가능(8~20자)',
			value: newPassword,
		},
		{
			title: '비밀번호 확인',
			name: 'passwordConfirm',
			placeholder: '비밀번호 재입력',
			value: passwordConfirm,
		},
	];

	// 완료 모달창
	const handleCompleteModal = () => {
		if (completeModal === 'hidden') {
			setCompleteModal('view');
		} else {
			setCompleteModal('hidden');

			if (confirmText === '변경이 완료되었습니다.') {
				sessionStorage.removeItem('token');
				navigate('/');
			}
		}
	};

	// 취소버튼
	const handleSessionout = e => {
		e.preventDefault();

		sessionStorage.removeItem('token');
		navigate('/');
	};

	return (
		<>
			<FormBox>
				<AccountTitle>비밀번호 재설정</AccountTitle>
				<FormWrapper action="" $flow="column" onSubmit={handleSubmit(onSubmitData)}>
					{/* 비밀번호 만료 안내에서 비밀번호 변경 시 현재 비밀번호 입력 항목이 보입니다. */}

					{AccountEditData.map((data, index) => (
						<AccountEditItem
							key={index}
							title={data.title}
							name={data.name}
							placeholder={data.placeholder}
							alertText={data.alertText}
							value={data.value}
							onChange={onChange}
							register={register}
							errors={errors}
						/>
					))}

					<PwBtnWrap $justify="space-between" $gap="14px">
						<Button
							theme="line"
							size="large"
							bordercolor="#e4e4e4"
							text="취소"
							handleClick={e => {
								handleSessionout(e);
							}}
							width="100%"
						/>

						<Button
							size="large"
							width="100%"
							text="완료"
							type="submit"
							bordercolor="#e4e4e4"
							theme={!values.passwordConfirm || errors.newPassword || errors.passwordConfirm ? 'disable' : 'primary'}
							isDisabled={values.password && values.newPassword && values.passwordConfirm ? false : true}
						/>
					</PwBtnWrap>
				</FormWrapper>
			</FormBox>
			{/* 완료 모달 */}
			<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={completeModal}>
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleCompleteModal} />
				</BtnWrapper>
				<ModalText $align="center">{confirmText}</ModalText>
				<BtnWrapper $gap="10px">
					<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleCompleteModal} />
				</BtnWrapper>
			</Modal>
		</>
	);
};

export default AccountEdit;

const PwBtnWrap = styled(BtnWrapper)`
	margin-top: 25px;
`;

const ButtonClose = styled.button`
	width: 16px;
	height: 16px;
	background: url(${CloseIcon}) 50% 50% no-repeat;
`;
