'use client';

import './style.scss';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useState, useEffect, useRef } from 'react';
import { ForgotPasswordRequest } from '@/dtos/request/auth';
import { fetchApi, throwError } from '@/lib/utils/client';
import { VerificationType } from '@/constants/common';
import Loading from '@/app/component/Loading';

export default function ForgotPassword()
{
    const router = useRouter();

    const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<string>('');
    const [email, setEmail] = useState<string>('');
	const emailRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
        if (error) {
            alert(error);
			setError('');
        }
    }, [error]);

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();

        try {

			setLoading(true);
        	setError('');

            if (!email) {
				emailRef.current?.focus();
                throw new Error('이메일을 입력해주세요.');
            }

            await new Promise(resolve => setTimeout(resolve, 500));

            const res = await fetchApi('/api/auth/forgot-password', {
                method: 'POST',
                body: { Email: email } as ForgotPasswordRequest
            });

			throwError(res);

			// 시간 제한 생성
			const expiration: string = (Date.now() + 10 * 60 * 1000).toString();
			const callbackURL: string = location.pathname;
			sessionStorage.setItem("type", VerificationType.ForgotPassword.toString());
			sessionStorage.setItem("expiration", expiration);
			sessionStorage.setItem("callbackURL", callbackURL);
			sessionStorage.setItem("email", email);
			router.push("/approval");

        } catch (err) {
            if (err instanceof Error) {
                setError(err.message);
            }
        } finally {
            setLoading(false);
        }
    }

    return (
		<>
			{loading && <Loading />}

			<div id="forgotPasswordForm" className="row-start-2">
				<fieldset>
					<legend>비밀번호 재설정</legend>
					<form method="post" acceptCharset="utf-8" autoComplete="off" className="grid pt-4 pl-4 pr-4 pb-1" onSubmit={handleSubmit}>
						<p>{process.env.SITE_NAME} 계정과 연결된 이메일 주소를 입력해주세요.</p>
						<p>해당 이메일로 인증번호가 발송되며 아래 입력란에 인증번호를 확인하면 비밀번호 재설정이 가능합니다.</p>

						<br />
						<label htmlFor="email">이메일</label>
						<input type="email" name="email" id="email" ref={emailRef} maxLength={30} onChange={e => setEmail(e.target.value)} autoComplete="off" />
						<button type="submit" className="btn btn-submit" disabled={loading}>
							{loading ? "조회 중..." : "다음 단계로"}
						</button>
						<hr />
						<Link href="/login">취소하기</Link>
					</form>
				</fieldset>
			</div>
		</>
    );
}