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

import { RegistValidation } from './RegistValidation';

import styled from 'styled-components';

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

import { AuthRegist } from '../../apis';

const AccountRegist = () => {
	const navigate = useNavigate();
	const [stateModal, setStateModal] = useState('hidden');
	const [submitText, setSubmitText] = useState('');
	const [doubleSubmitFlag, setDoubleSubmitFlag] = useState(false);
	const [isSuccess, setIsSuccess] = useState(false)

	const handleModal = () => {
		if (stateModal === 'hidden') {
			setStateModal('view');
		} else {
			// submitText === '회원가입이 완료되었습니다. \n 관리자 로그인 권한 승인 까지 \n 대기해주세요.' ? navigate('/') : setStateModal('hidden'); //2024.08.02 승인 제외에 따른 변경
			isSuccess ? navigate('/') : setStateModal('hidden');
			setDoubleSubmitFlag(false);
		}
	};

	const onSubmitData = async data => {
		setDoubleSubmitFlag(true);

		const result = await AuthRegist(data);
		
		setSubmitText(
			// result.data.access_token && result.data.access_token === '저장 하였습니다.' ? '회원가입이 완료되었습니다. \n 관리자 로그인 권한 승인 까지 \n 대기해주세요.' : result.data.message, //2024.08.02 승인 제외에 따른 메시지 변경
			result.data.access_token && result.data.access_token === '저장 하였습니다.' ? '회원가입이 완료되었습니다.' : result.data.message,
		);
		setIsSuccess(result.data.access_token && result.data.access_token === '저장 하였습니다.' ? true : false);

		handleModal();
	};

	// console.log(doubleSubmitFlag);

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

	const [form, setForm] = useState({
		username: '',
		userid: '',
		password: '',
		confirmPassword: '',
	});

	const { username, userid, password, confirmPassword } = form;

	const values = watch();

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

	const AccountRegistData = [
		{
			title: '이름',
			type: 'text',
			name: 'username',
			placeholder: '한글, 영문 입력 가능',
			value: username,
		},
		{
			title: 'ID(메일주소)',
			type: 'text',
			name: 'userid',
			placeholder: 'sample@lotte.net',
			value: userid,
		},
		{
			title: '비밀번호',
			type: 'password',
			name: 'password',
			placeholder: '영어/숫자/특수문자 조합 가능(8~20자)',
			value: password,
			length: '20',
		},
		{
			title: '비밀번호 확인',
			type: 'password',
			name: 'confirmPassword',
			placeholder: '비밀번호 확인',
			value: confirmPassword,
			length: '20',
		},
	];

	return (
		<>
			<FormBox>
				<AccountTitle>회원가입</AccountTitle>
				<FormWrapper $flow="column" onSubmit={doubleSubmitFlag || handleSubmit(onSubmitData)}>
					{AccountRegistData.map((data, index) => (
						<AccountInputItem
							key={index}
							title={data.title}
							type={data.type}
							name={data.name}
							placeholder={data.placeholder}
							alertText={data.alertText}
							value={data.value}
							onChange={onChange}
							register={register}
							errors={errors}
							length={data.length && data.length}
						/>
					))}
					<JoinBtnWrapper $justify="space-between" $gap="14px">
						<Button
							theme="line"
							size="large"
							text="취소"
							width="100%"
							handleClick={e => {
								e.preventDefault();
								navigate('/');
							}}
							bordercolor="#e4e4e4"
						/>

						<Button
							errorMessage={doubleSubmitFlag === true}
							size="large"
							text="가입하기"
							type="submit"
							width="100%"
							theme={!values.confirmPassword || errors.username || errors.userid || errors.password || errors.confirmPassword ? 'disable' : 'primary'}
						/>
					</JoinBtnWrapper>
				</FormWrapper>
			</FormBox>
			<Modal $view={stateModal} min="440px" $padding="40px">
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleModal} />
				</BtnWrapper>
				<ModalText>{submitText}</ModalText>
				<Button text="확인" theme="primary" size="large" width="100%" handleClick={handleModal} />
			</Modal>
		</>
	);
};

export default AccountRegist;

const JoinBtnWrapper = styled(BtnWrapper)`
	margin-top: 25px;
	justify-content: space-between;
	gap: 14px;
`;

const ModalText = styled.div`
	font-size: 20px;
	line-height: 30px;
	font-weight: 600;
	padding: 10px 0 40px;
`;

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