'use client';

import '../[code]/style.scss';
import { useRouter } from 'next/navigation';
import { useCallback } from 'react';
import useAuth from '@/hooks/useAuth';
import { checkPermission } from '@/lib/utils/permission';
import BoardMeta from '@/types/forum/boardMeta';
import BoardManager from '@/types/forum/boardManager';

type Props = {
	alwaysShowButton: boolean;
	boardCode: string;
	boardMeta: BoardMeta;
	boardManagers: BoardManager[];
}

export default function PostWriteButton({ alwaysShowButton, boardCode, boardMeta, boardManagers }: Props)
{
	const router = useRouter();
	const { isAuthenticated, member, loginCheck } = useAuth();

	const handleClick = useCallback((e: React.MouseEvent<HTMLButtonElement>) => {
		try {

			if (!isAuthenticated) {
				throw new Error('로그인 후 이용해주세요.');
			}

			// 게시글 작성 권한 확인
			if (!checkPermission(boardMeta, boardManagers, member).canWritePost) {
				throw new Error('글을 작성할 수 있는 권한이 없습니다.');
			}

			router.push(e.currentTarget.value);

		} catch(err) {
			if (err instanceof Error) {
				return alert(err.message);
			}
		}
	}, [loginCheck, boardMeta, boardManagers, member, router]);

	if (!alwaysShowButton && !isAuthenticated) {
		return null;
	}

	return (
		<>
			<section aria-label='글쓰기 버튼'>
				<button type="button" value={`/post/write?board=${boardCode}`} className='btn btn-submit' onClick={handleClick}>글쓰기</button>
			</section>
		</>
	);
}