'use client';

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

export default function ChangeName()
{
	const config = useConfigContext();
	const { member, setMember } = useMemberContext();
	const { setError } = useErrorAlert();
	const [loading, setLoading] = useState<boolean>(false);
	const [newName, setNewName] = useState<string>('');
	const newNameRef = useRef<HTMLInputElement>(null);

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

		if (!member) {
			return;
		}

		if (!newName) {
			newNameRef.current?.focus();
			return setError('별명을 입력하세요.');
		}

		setLoading(true);

		fetchApi('/api/mypage/name', {
			method: 'POST',
			body: { Name: newName } as ChangeNameRequest
		}).then((res) => {
			throwError(res);

			member.name = newName;
			setMember(member);
			localStorage.setItem('member', JSON.stringify(member));

			alert("별명이 변경되었습니다.");
		}).catch(err => {
			setError(err.message);
		}).finally(() => {
			setLoading(false);
			setNewName('');
		});
	}

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

	const handleDelete = async () => {
		if (confirm("별명을 삭제하시겠습니까?")) {
			if (!member || !member.name) {
				return;
			}

			setLoading(true);

			fetchApi('/api/mypage/name', { method: 'DELETE' }).then((res) => {
				throwError(res);

				member.name = null;
				setMember(member);
				localStorage.setItem('member', JSON.stringify(member));

				alert("별명이 삭제되었습니다.");
			}).catch(err => {
				setError(err.message);
			}).finally(() => {
				setLoading(false);
				setNewName('');
			});
		}
	};

	return (
		<>
		<div id="changeName">
			{ 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>
						개성을 담아 별명을 지어보세요!<br />
						일 간격으로 별명을 변경할 수 있습니다.
					</caption>
					<colgroup>
						<col width="30%"/>
						<col width="60%"/>
						<col width="10%"/>
					</colgroup>
					<tbody>
						<tr>
							<th>현재 별명</th>
							<td>{member?.name ?? '-'}</td>
							<td>&nbsp;</td>
						</tr>
						<tr>
							<th>새 별명</th>
							<td>
								<input type="text" name="new_name" id="newName" ref={newNameRef} value={newName} placeholder="변경할 별명" maxLength={20} autoFocus autoComplete="off" onChange={handleChange} />
							</td>
							<td>&nbsp;</td>
						</tr>
					</tbody>
					<tfoot>
						<tr>
							<td colSpan={3}>
								<div className="flex justify-center gap-2">
									<button type="submit" className="btn btn-submit">확인</button>
									{ member?.name && (
										<button type="button" className="btn btn-delete" onClick={handleDelete}>삭제</button>
									)}
									<Link href="/profile" className="btn btn-default">취소</Link>
								</div>
							</td>
						</tr>
					</tfoot>
				</table>
			</form>
			<br />
			<dl className="max-xl:w-full lg:w-[600px]">
				<dt>등록할 수 없는 별명</dt>
				<dd>
					<ol>
						<li>별명은 최대 20자 이내로 입력 가능합니다.</li>
						<li>욕설 및 비속어는 별명으로 만들 수 없습니다.</li>
						<li>부적절한 별명은 별도의 고지 없이 변경될 수 있습니다.</li>
						{config.account.changeNameDay > 0 && <li>별명 변경 주기는 {config.account.changeNameDay}일입니다.</li>}
					</ol>
				</dd>
			</dl>
		</div>
		</>
	);
}