'use client';

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

export default function LoginLog()
{
	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 [logs, setLogs] = useState<LoginLogsResponse>({
		total: 0,
		list: []
	});

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

	useEffect(() => {
		setLoading(true);
		fetchApi<LoginLogsResponse>(`/api/mypage/login-logs?type=${type}&page=${page}&perPage=20`).then((res) => {
			throwError(res);
			setLogs(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="loginLog" >
			{ 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>
							합계： {logs.total}
						</div>
						<div id="loginTypeTab" 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 />
					<col />
					<col width="15%"/>
				</colgroup>
				<thead>
					<tr>
						<th>일시</th>
						<th>접속 IP</th>
						<th>접속 기기</th>
						<th>브라우저</th>
						<th>결과</th>
					</tr>
				</thead>
				<tbody>
					{logs.list.length > 0 ? (
						logs.list.map((row) => {
							return (
								<tr key={row.id} className="hover:bg-gray-100">
									<td>{row.createdAt}</td>
									<td>{row.ipAddress}</td>
									<td>{row.ipAddress}</td>
									<td>{row.userAgent}</td>
									<td className={`border p-2 font-semibold ${row.success ? "text-green-500" : "text-red-500"}`}>
										{row.success ? "성공" : "실패"}
									</td>
								</tr>
							);
						})
						) : (
							<tr>
								<td colSpan={5} className="border p-2 text-center text-gray-500">
									기록이 없습니다.
								</td>
							</tr>
						)}
				</tbody>
				{logs.list.length > 0 && (
				<tfoot>
					<tr>
						<td colSpan={5}>
							<Pagination total={logs.total} page={page} perPage={20} onChange={setPage} />
						</td>
					</tr>
				</tfoot>
				)}
			</table>
		</div>
		</>
	);
}