'use client';

import './style.scss';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { fetchApi, throwError, getDateTime } from '@/lib/utils/client';
import type { MyCommentsResponse } from '@/types/response/account/myComments';
import Loading from '@/app/component/Loading';
import Pagination from '@/app/component/Pagination';
import NavTabs from '../navTabs';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faThumbsUp } from '@fortawesome/free-regular-svg-icons';

export default function MyComments()
{
	const [error, setError] = useState<string>('');
	const [loading, setLoading] = useState<boolean>(true);
	const [page, setPage] = useState<number>(1);
	const [data, setData] = useState<MyCommentsResponse>({
		total: 0,
		list: []
	});

	useEffect(() => {
		if (error) {
			alert(error);
			setError('');
		}
	}, [error]);

	useEffect(() => {
		setLoading(true);
		fetchApi<MyCommentsResponse>(`/api/mypage/comments?page=${page}&perPage=20`).then((res) => {
			throwError(res);
			setData(res.data!);
		}).catch(err => {
			setError(err.message);
		}).finally(() => {
			setLoading(false);
		});
	}, [page]);

	return (
		<>
		<NavTabs />

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

			<h1>작성 댓글</h1>
			<div className="summary">합계： {data.total}</div>

			<section className="mypage-list">
				<article>
					<ul>
						<li>번호</li>
						<li>게시판</li>
						<li>게시글</li>
						<li>댓글 내용</li>
						<li>추천</li>
						<li>작성일</li>
					</ul>
				</article>
				<article>
					{data.list.length > 0 ? (
						data.list.map((row) => (
							<section key={row.id}>
								{/* PC */}
								<ol>
									<li>{row.num}</li>
									<li>{row.boardName}</li>
									<li>
										<Link href={`/post/${row.postID}`}>
											<em>{row.postSubject}</em>
										</Link>
									</li>
									<li className="comment-content">{row.content}</li>
									<li>{row.likes}</li>
									<li>{getDateTime(row.createdAt)}</li>
								</ol>

								{/* Mobile */}
								<dl hidden>
									<dt>{row.content}</dt>
									<dd>
										<ul>
											<li>
												<Link href={`/post/${row.postID}`}>
													[{row.boardName}] {row.postSubject}
												</Link>
											</li>
											<li><FontAwesomeIcon icon={faThumbsUp} /> {row.likes}</li>
											<li>{getDateTime(row.createdAt)}</li>
										</ul>
									</dd>
								</dl>
							</section>
						))
					) : (
						<p className="empty">작성한 댓글이 없습니다.</p>
					)}
				</article>
			</section>

			{data.list.length > 0 && (
				<Pagination total={data.total} page={page} perPage={20} onChange={setPage} />
			)}
		</div>
		</>
	);
}
