'use client';

import './style.scss';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { fetchApi, throwError, formatDate } 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';

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>
			<table className="table-auto max-2xl:w-full 2xl:w-[1000px]">
				<caption>
					<div>
						합계： {data.total}
					</div>
				</caption>
				<colgroup>
					<col width="8%"/>
					<col width="12%"/>
					<col width="20%"/>
					<col />
					<col width="10%"/>
					<col width="15%"/>
				</colgroup>
				<thead>
					<tr>
						<th>번호</th>
						<th>게시판</th>
						<th>게시글</th>
						<th>댓글 내용</th>
						<th>추천</th>
						<th>작성일</th>
					</tr>
				</thead>
				<tbody>
					{data.list.length > 0 ? (
						data.list.map((row) => (
							<tr key={row.id} className="hover:bg-gray-100">
								<td>{row.num}</td>
								<td>{row.boardName}</td>
								<td className="text-left">
									<Link href={`/post/${row.postID}`}>{row.postSubject}</Link>
								</td>
								<td className="text-left">{row.content}</td>
								<td>{row.likes}</td>
								<td>{formatDate(row.createdAt)}</td>
							</tr>
						))
					) : (
						<tr>
							<td colSpan={6} className="border p-2 text-center text-gray-500">
								작성한 댓글이 없습니다.
							</td>
						</tr>
					)}
				</tbody>
				{data.list.length > 0 && (
				<tfoot>
					<tr>
						<td colSpan={6}>
							<Pagination total={data.total} page={page} perPage={20} onChange={setPage} />
						</td>
					</tr>
				</tfoot>
				)}
			</table>
		</div>
		</>
	);
}