'use client';

import './style.scss';
import Link from 'next/link';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useConfigContext } from '@/contexts/configProvider';
import { useMemberContext } from '@/contexts/memberProvider';
import useErrorAlert from '@/hooks/useErrorAlert';
import { ChangePasswordRequest } from '@/types/request/account';
import { fetchApi, getPasswordPolicyMessage } from '@/lib/utils/client';
import Loading from '@/app/component/Loading';
import NavTabs from '../navTabs';

export default function ChangePassword()
{
	const config = useConfigContext();
	const { member } = useMemberContext();
	const { setError } = useErrorAlert();
	const [loading, setLoading] = useState<boolean>(false);
	const [isComplete, setComplete] = useState<boolean>(false);
	const [formData, setFormData] = useState({
		currentPassword: '',
		newPassword: '',
		confirmPassword: ''
	});
	const currentPasswordRef = useRef<HTMLInputElement>(null);
	const newPasswordRef = useRef<HTMLInputElement>(null);
	const confirmPasswordRef = useRef<HTMLInputElement>(null);

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

		if (!member) {
			return;
		}

		if (!formData.currentPassword) {
			setError("현재 비밀번호를 입력하세요.");
			currentPasswordRef.current?.focus();
			return;
		}

		if (!formData.newPassword) {
			setError("새 비밀번호를 입력하세요.");
			newPasswordRef.current?.focus();
			return;
		}

		if (!formData.confirmPassword) {
			setError("새 비밀번호 확인을 입력하세요.");
			confirmPasswordRef.current?.focus();
			return;
		}

		if (formData.newPassword !== formData.confirmPassword) {
			setError("새 비밀번호가 일치하지 않습니다.");
			return;
		}

		if (formData.currentPassword === formData.newPassword) {
			setError("새 비밀번호는 현재 비밀번호와 달라야 합니다.");
			return;
		}

		setLoading(true);

		fetchApi('/api/mypage/password', {
			method: 'POST',
			body: {
				CurrentPassword: formData.currentPassword,
				NewPassword: formData.newPassword,
				ConfirmPassword: formData.confirmPassword
			} as ChangePasswordRequest
		}).then(() => {
			setComplete(true);
		}).catch(err => {
			setError(err.message);
		}).finally(() => {
			setLoading(false);
		});
	}

	const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
		const { id, value } = e.target;
		setFormData(prev => ({ ...prev, [id]: value}));
	}, []);

	useEffect(() => {
		if (isComplete)
		{
			// 입력 초기화
			setFormData({
				currentPassword: '',
				newPassword: '',
				confirmPassword: ''
			});

			setComplete(false);
			alert("비밀번호가 변경되었습니다.");
		}
	}, [isComplete]);

	const txtPasswordGuide = getPasswordPolicyMessage({
		passwordUppercaseLength: config.account.passwordUppercaseLength ?? 0,
		passwordNumbersLength: config.account.passwordNumbersLength ?? 0,
		passwordSpecialcharsLength: config.account.passwordSpecialcharsLength ?? 0
	});

	return (
		<>
		<NavTabs />

		<div id="changePassword">
			{ loading && <Loading /> }

			<h1>비밀번호 변경</h1>
			<form method="post" acceptCharset="utf-8" autoComplete="off" onSubmit={handleSubmit}>
				<table className="table-auto max-xl:w-full lg:w-[600px]">
					<caption>
						비밀번호는 { config.account.passwordMinLength }자 이상 20자 이하로 설정 가능합니다.<br />
						{ txtPasswordGuide }
					</caption>
					<colgroup>
						<col width="30%"/>
						<col width="60%"/>
						<col width="10%"/>
					</colgroup>
					<tbody>
						<tr>
							<th><label htmlFor='currentPassword'>현재 비밀번호</label></th>
							<td>
								<input type="password" id="currentPassword" value={formData.currentPassword} onChange={handleChange} placeholder="현재 비밀번호" ref={currentPasswordRef} />
							</td>
							<td>&nbsp;</td>
						</tr>
						<tr>
							<th><label htmlFor='newPassword'>새 비밀번호</label></th>
							<td>
								<input type="password" id="newPassword" value={formData.newPassword} onChange={handleChange} placeholder="새 비밀번호" ref={newPasswordRef} />
							</td>
							<td>&nbsp;</td>
						</tr>
						<tr>
							<th><label htmlFor='confirmPassword'>새 비밀번호 확인</label></th>
							<td>
								<input type="password" id="confirmPassword" value={formData.confirmPassword} onChange={handleChange} placeholder="새 비밀번호 확인" ref={confirmPasswordRef} />
							</td>
							<td>&nbsp;</td>
						</tr>
					</tbody>
					<tfoot>
						<tr>
							<td colSpan={3}>
								<div className="flex justify-center gap-2">
									<button type="submit" className="btn btn-primary">확인</button>
									<Link href="/profile" className="btn btn-default">취소</Link>
								</div>
							</td>
						</tr>
					</tfoot>
				</table>
			</form>
		</div>
		</>
	);
}