'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 { MyPostsResponse } from '@/types/response/account/myPosts';
import Loading from '@/app/component/Loading';
import Pagination from '@/app/component/Pagination';
import NavTabs from '../navTabs';

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

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

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

	return (
		<>
		<NavTabs />

		<div id="myPosts">
			{ 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 />
					<col width="10%"/>
					<col width="10%"/>
					<col width="10%"/>
					<col width="15%"/>
				</colgroup>
				<thead>
					<tr>
						<th>번호</th>
						<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.id}`}>{row.subject}</Link>
								</td>
								<td>{row.views}</td>
								<td>{row.likes}</td>
								<td>{row.comments}</td>
								<td>{formatDate(row.createdAt)}</td>
							</tr>
						))
					) : (
						<tr>
							<td colSpan={7} className="border p-2 text-center text-gray-500">
								작성한 게시글이 없습니다.
							</td>
						</tr>
					)}
				</tbody>
				{data.list.length > 0 && (
				<tfoot>
					<tr>
						<td colSpan={7}>
							<Pagination total={data.total} page={page} perPage={20} onChange={setPage} />
						</td>
					</tr>
				</tfoot>
				)}
			</table>
		</div>
		</>
	);
}