'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 { ChangeSummaryRequest } from '@/types/request/account';
import { fetchApi, throwError } from '@/lib/utils/client';
import Loading from '@/app/component/Loading';

export default function ChangeSummary()
{
	const config = useConfigContext();
	const { member, setMember } = useMemberContext();
	const { setError } = useErrorAlert();
	const [loading, setLoading] = useState<boolean>(false);
	const [newSummary, setNewSummary] = useState<string|null>('');
	const newSummaryRef = useRef<HTMLInputElement>(null);

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

		if (!member) {
			return;
		}

		if (!newSummary) {
			newSummaryRef.current?.focus();
			return setError('한마디를 입력하세요.');
		}

		setLoading(true);

		fetchApi('/api/mypage/summary', {
			method: 'POST',
			body: { Summary: newSummary } as ChangeSummaryRequest
		}).then((res) => {
			throwError(res);

			member.summary = newSummary;
			setMember(member);
			localStorage.setItem('member', JSON.stringify(member));
			alert('한마디가 변경되었습니다.');

		}).catch(err => {
			setError(err.message);
		}).finally(() => {
			setLoading(false);
			setNewSummary('');
		});
	}

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

	const handleDelete = async () => {
		if (confirm("한마디를 삭제하시겠습니까?")) {
			if (!member || !member.summary) {
				return;
			}

			setLoading(true);

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

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

				alert("한마디를 삭제되었습니다.");
			}).catch(err => {
				setError(err.message);
			}).finally(() => {
				setLoading(false);
				setNewSummary('');
			});
		}
	};

	return (
		<>
		<div id='changeSummary'>
			{ 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>
						커뮤니티 프로필에 표시되는 한마디를 설정할 수 있습니다.
					</caption>
					<colgroup>
						<col width='30%'/>
						<col width='60%'/>
						<col width='10%'/>
					</colgroup>
					<tbody>
						<tr>
							<th>현재 한마디</th>
							<td>{member?.summary || '-'}</td>
							<td>&nbsp;</td>
						</tr>
						<tr>
							<th>새 한마디</th>
							<td>
								<input type='text' name='new_summary' id='newSummary' ref={newSummaryRef} value={newSummary ?? ''} placeholder='변경할 한마디' maxLength={50} 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?.summary && (
										<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>한마디는 최대 50자 이내로 입력 가능합니다.</li>
						<li>부적절한 내용은 별도의 고지 없이 변경될 수 있습니다.</li>
						{config.account.changeSummaryDay > 0 && <li>자기소개개 변경 주기는 {config.account.changeSummaryDay}일입니다.</li>}
					</ol>
				</dd>
			</dl>
		</div>
		</>
	);
}