'use client';

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

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

	const [loading, setLoading] = useState<boolean>(false);
    const [error, setError] = useState<string>('');
	const [password, setPassword] = useState<string>('');
    const [rePassword, setRePassword] = useState<string>('');
    const [email, setEmail] = useState<string|null>(null);
    const passwordRef = useRef<HTMLInputElement>(null);
    const rePasswordRef = useRef<HTMLInputElement>(null);

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

    useEffect(() => {
        const storedEmail = sessionStorage.getItem('email');

        if (!storedEmail) {
            setError('잘못된 접근입니다.');
            router.push('/login');
            return;
        }

        setEmail(storedEmail);
    }, [router]);

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

        try {

            setLoading(true);
            setError('');

            if (!email) {
                throw new Error("이메일을 입력하세요.");
            }

            if (!password) {
                passwordRef.current?.focus();
                throw new Error("비밀번호를 입력하세요.");
            }

            if (!rePassword) {
                rePasswordRef.current?.focus();
                throw new Error("비밀번호를 입력하세요.");
            }

            if (password !== rePassword) {
                throw new Error("비밀번호가 일치하지 않습니다.");
            }

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

            const res = await fetchApi('/api/auth/reset-password', {
                method: 'POST',
                body: { Email: email, Password: password, RePassword: rePassword } as ResetPasswordRequest
            });

            throwError(res);

			sessionStorage.clear();
			alert(res.message);
			router.push('/login');

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

    return (
		<>
		{loading && <Loading />}
        <div id="resetPasswordForm" className="row-start-2">
            <fieldset>
                <legend>비밀번호 변경</legend>
                <form id="fResetPassword" method="post" acceptCharset="utf-8" autoComplete="off" onSubmit={handleSubmit}>
                    <section className="grow sm:pt-4">
                        <article className="grid">
                            <label htmlFor="email">이메일</label>
                            <input type="email" name="email" id="email" value={email || ''} disabled />

                            <label htmlFor="password">비밀번호</label>
                            <input type="password" name="password" id="password" ref={passwordRef} maxLength={20} value={password} onChange={e => setPassword(e.target.value)} />

                            <label htmlFor="rePassword">비밀번호 확인</label>
                            <input type="password" name="re_password" id="rePassword" ref={rePasswordRef} maxLength={20} value={rePassword} onChange={e => setRePassword(e.target.value)} />
                        </article>
                    </section>
                    <hr />
                    <div className="grid grid-cols-2 gap-2">
                        <button type="submit" className="btn btn-submit" disabled={loading}>
                            {loading ? "변경 중..." : "변경하기"}
                        </button>
                        <Link href="/login" className="btn btn-default">취소</Link>
                    </div>
                </form>
            </fieldset>
        </div>
		</>
    );
}