'use client';

import './style.scss';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useMemo } from 'react'
import Post from '@/types/forum/post';
import { formatDate, isNewPost } from '@/lib/utils/client';
import { BoardLayout } from '@/constants/forum';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faComment, faThumbsUp, faEye } from '@fortawesome/free-regular-svg-icons';

type Props = {
	isEnabled: boolean;
	list: Post[];
	layout?: BoardLayout;
}

// 공지사항 목록
export default function NoticeListLayout({isEnabled, list, layout}: Props)
{
	const searchParams = useSearchParams();
	const query = useMemo(() => Object.fromEntries(searchParams.entries()), [searchParams]);

	if (!isEnabled) {
		return null;
	}

	if (!list || list.length <= 0) {
		return;
	}

	return (
		<>
			{list.map(row => {
				const isNew = isNewPost(true, row);
				const createdAt = formatDate(row.createdAt);
				const postViewUrl = {pathname: '/post/' + row.id, query};

				return (
					<section key={row.id}>
						{/* PC */}
						<ol>
							<li>
								<img src='/resources/notice.gif' alt='공지사항' className='mx-auto'/>
							</li>
							<li>
								<Link href={postViewUrl}>
									<em>{row.subject} {row.comments > 0 && (<span>[{row.comments}]</span>)}</em>
									{isNew && <span><img src='/resources/new.gif' alt='NEW'/></span>}
								</Link>
							</li>


							{layout === BoardLayout.Default && (
							<>
								<li>{row.name || row.sid}</li>
								<li>{createdAt}</li>
								<li>{row.views}</li>
								<li>{row.likes}</li>
							</>
							)}

							{layout === BoardLayout.Media && (
							<>
								<li>{row.name || row.sid}</li>
								<li>{createdAt}</li>
								<li>{row.views}</li>
							</>
							)}

							{layout === BoardLayout.QnA && (
							<>
								<li>{row.name || row.sid}</li>
								<li>-</li>
								<li>{createdAt}</li>
							</>
							)}
						</ol>

						{/* Mobile */}
						<dl hidden>
							<dt>
								<Link href={postViewUrl}>
									<em>{row.subject} {row.comments > 0 && (<span>[{row.comments}]</span>)}</em>
									{isNew && <span><img src='/resources/new.gif' alt='NEW'/></span>}
								</Link>
							</dt>
							<dd>
								<ul>
									<li>{row.name || row.sid}</li>
									<li><FontAwesomeIcon icon={faComment} /> {row.comments}</li>
									<li><FontAwesomeIcon icon={faEye} /> {row.views}</li>
									<li><FontAwesomeIcon icon={faThumbsUp} /> {row.likes}</li>
									<li>{createdAt}</li>
								</ul>
							</dd>
						</dl>
					</section>
				);
			})}
		</>
	);
}