'use client';

import './style.scss';
import { useState, useEffect } from 'react';
import { LoginLogType } from '@/constants/common';
import { fetchApi, throwError, getDateTime } from '@/lib/utils/client';
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>
			<div className="list-header">
				<div className="summary">합계： {logs.total}</div>
				<div id="loginTypeTab">
					{tabItems.map((item, i) => (
						<button type="button" key={i} className={type === item.value ? 'active' : ''}
							onClick={() => setType(item.value)}>{item.label}
						</button>
					))}
				</div>
			</div>

			<section className="mypage-list">
				<article>
					<ul>
						<li>일시</li>
						<li>접속 IP</li>
						<li>접속 기기</li>
						<li>브라우저</li>
						<li>결과</li>
					</ul>
				</article>
				<article>
					{logs.list.length > 0 ? (
						logs.list.map((row) => (
							<section key={row.id}>
								{/* PC */}
								<ol>
									<li>{getDateTime(row.createdAt)}</li>
									<li>{row.ipAddress}</li>
									<li>{row.ipAddress}</li>
									<li className="ua">{row.userAgent}</li>
									<li>
										<span className={row.success ? 'badge-success' : 'badge-fail'}>
											{row.success ? '성공' : '실패'}
										</span>
									</li>
								</ol>

								{/* Mobile */}
								<dl hidden>
									<dt>
										{getDateTime(row.createdAt)}
										<span className={row.success ? 'badge-success' : 'badge-fail'}>
											{row.success ? '성공' : '실패'}
										</span>
									</dt>
									<dd>
										<ul>
											<li>{row.ipAddress}</li>
											<li className="ua">{row.userAgent}</li>
										</ul>
									</dd>
								</dl>
							</section>
						))
					) : (
						<p className="empty">기록이 없습니다.</p>
					)}
				</article>
			</section>

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