'use client';

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

const STATUS_MAP: Record<string, { label: string; cls: string }> = {
	Paid: { label: '완료', cls: 'status--paid' },
	Pending: { label: '대기', cls: 'status--pending' },
	WaitingDeposit: { label: '입금대기', cls: 'status--pending' },
	Failed: { label: '실패', cls: 'status--failed' },
	Cancelled: { label: '취소', cls: 'status--cancelled' }
};

const METHOD_MAP: Record<string, string> = {
	Card: '신용카드',
	VirtualAccount: '가상계좌',
	Mobile: '휴대폰',
	Transfer: '계좌이체',
	NaverPay: '네이버페이',
	KakaoPay: '카카오페이',
	Payco: '페이코',
	Integrated: '통합결제'
};

export default function ChargeLogs()
{
	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<ChargeLogsResponse>({
		total: 0,
		list: []
	});

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

	useEffect(() => {
		setLoading(true);

		fetchApi<ChargeLogsResponse>(`/api/mypage/charge-logs?type=${type}&page=${page}&perPage=20`).then((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 }
	];

	const getStatus = (status: string) => STATUS_MAP[status] ?? { label: status, cls: '' };
	const getMethod = (method: string) => METHOD_MAP[method] ?? method;

	return (
		<>
		<NavTabs />

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

			<h1>(P) 충전 내역</h1>
			<div className="charge-logs__header">
				<div className="charge-logs__summary">합계: {data.total}</div>
				<div className="charge-logs__tabs">
					{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="charge-logs__list">
				<article>
					<ul>
						<li>일시</li>
						<li>주문번호</li>
						<li>결제 수단</li>
						<li>결제 금액</li>
						<li>포인트</li>
						<li>상태</li>
					</ul>
				</article>
				<article>
					{data.list.length > 0 ? (
						data.list.map((row) => {
							const st = getStatus(row.status);
							return (
								<section key={row.id}>
									{/* PC */}
									<ol>
										<li>{getDateTime(row.paidAt ?? row.createdAt)}</li>
										<li className="charge-logs__order-id">{row.orderID}</li>
										<li>{getMethod(row.paymentMethod)}</li>
										<li>{row.amount.toLocaleString()}원</li>
										<li className="amount-plus">+{row.pointAmount.toLocaleString()}P</li>
										<li><span className={st.cls}>{st.label}</span></li>
									</ol>

									{/* Mobile */}
									<dl hidden>
										<dt>
											<div className='flex justify-between'>
												<div>{row.amount.toLocaleString()}원 충전</div>
												<div>
													<small className="charge-logs__order-id">{row.orderID}</small>
												</div>
											</div>
										</dt>
										<dd>
											<ul>
												<li className="amount-plus">+{row.pointAmount.toLocaleString()}P</li>
												<li><span className={st.cls}>{st.label}</span></li>
												<li>{getDateTime(row.paidAt ?? row.createdAt)}</li>
											</ul>
										</dd>
									</dl>
								</section>
							);
						})
					) : (
						<p className="empty">충전 기록이 없습니다.</p>
					)}
				</article>
			</section>

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