'use client';

import './style.scss';
import { useState, useEffect } from 'react';
import { LoginLogType } from '@/constants/common';
import { fetchApi, throwError, formatDate } from '@/lib/utils/client';
import type { ExpLogsResponse } from '@/types/response/account/expLogs';
import Loading from '@/app/component/Loading';
import Pagination from '@/app/component/Pagination';
import NavTabs from '../navTabs';

export default function ExpLogs()
{
	const [error, setError] = useState<string>('');
	const [loading, setLoading] = useState<boolean>(true);
	const [page, setPage] = useState<number>(1);
	const [type, setType] = useState<LoginLogType>(LoginLogType.Today);
	const [data, setData] = useState<ExpLogsResponse>({
		total: 0,
		list: []
	});

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

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

	useEffect(() => {
		setPage(1);
	}, [type]);

	const tabItems = [
		{ label: "오늘", value: LoginLogType.Today },
		{ label: "1주일", value: LoginLogType.Week },
		{ label: "1개월", value: LoginLogType.Month },
		{ label: "3개월", value: LoginLogType.QuarterYear },
		{ label: "6개월", value: LoginLogType.HalfYear }
	];

	return (
		<>
		<NavTabs />

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

			<h1>경험치 내역</h1>
			<table className="table-auto max-2xl:w-full 2xl:w-[1000px]">
				<caption>
					<div className="grid grid-cols-[auto,1fr] gap-4 items-center">
						<div>
							합계： {data.total}
						</div>
						<div id="expTypeTab" className="justify-self-end">
							{tabItems.map((item, i) => (
								<button type="button" key={i} className={`flex-1 py-2 px-4 text-center text-sm font-medium
									${type === item.value ? "border-b-2 border-blue-500 text-blue-500" : "text-gray-500"}
								`} onClick={() => setType(item.value)}>{item.label}
								</button>
							))}
						</div>
					</div>
				</caption>
				<colgroup>
					<col width="20%"/>
					<col />
					<col width="15%"/>
					<col width="15%"/>
				</colgroup>
				<thead>
					<tr>
						<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>{formatDate(row.createdAt)}</td>
								<td>{row.reason}</td>
								<td className={`font-semibold ${row.amount > 0 ? "text-green-500" : "text-red-500"}`}>
									{row.amount > 0 ? `+${row.amount}` : row.amount}
								</td>
								<td>{row.balance.toLocaleString()}</td>
							</tr>
						))
					) : (
						<tr>
							<td colSpan={4} className="border p-2 text-center text-gray-500">
								기록이 없습니다.
							</td>
						</tr>
					)}
				</tbody>
				{data.list.length > 0 && (
				<tfoot>
					<tr>
						<td colSpan={4}>
							<Pagination total={data.total} page={page} perPage={20} onChange={setPage} />
						</td>
					</tr>
				</tfoot>
				)}
			</table>
		</div>
		</>
	);
}