'use client';

import { useCallback, useEffect, useState } from 'react';
import { fetchApi } from '@/lib/utils/client';
import Loading from '@/app/component/Loading';
import Pagination from '@/app/component/Pagination';
import NavTabs from '../navTabs';
import { ITEM_KIND_LABEL, ITEM_KIND_DESC, DIRECT_USE_KINDS } from '@/types/account/items';
import type { MemberItemRow, MemberItemsResponse, UseItemResult } from '@/types/account/items';

const PER_PAGE = 20;

export default function MemberItemsPage()
{
	const [items, setItems] = useState<MemberItemRow[]>([]);
	const [total, setTotal] = useState(0);
	const [page, setPage] = useState(1);
	const [loading, setLoading] = useState(true);
	const [busyID, setBusyID] = useState<number|null>(null);

	const load = useCallback(async () => {
		setLoading(true);

		const res = await fetchApi<MemberItemsResponse>(`/api/member/me/items?page=${page}&perPage=${PER_PAGE}`, { silent: true });

		if (res.success && res.data) {
			setItems(res.data.list);
			setTotal(res.data.total);
		}
		else {
			setItems([]);
			setTotal(0);
		}

		setLoading(false);
	}, [page]);

	useEffect(() => {
		load();
	}, [load]);

	const useItem = async (item: MemberItemRow) => {
		if (item.kind === 'PostReset' && !confirm('신고·댓글이 없는 예전 게시글이 모두 삭제됩니다. 계속하시겠어요?')) {
			return;
		}

		setBusyID(item.id);

		const res = await fetchApi<UseItemResult>(`/api/member/me/items/${item.id}/use`, { method: 'POST', silent: true });

		setBusyID(null);

		if (res.success && res.data) {
			alert(res.data.message || '아이템을 사용했습니다.');
			await load();
		}
		else {
			alert(res.message || '아이템 사용에 실패했습니다.');
		}
	};

	return (
		<>
			<NavTabs />

			<div className='mx-auto px-4 sm:px-8 pb-8'>
				<h1 className='text-2xl font-bold mb-1'>아이템</h1>
				<p className='text-sm text-neutral-500 mb-4'>
					상점에서 구매한 소모품 아이템입니다. 채팅 밴 해제·예전 글 초기화·경험치 부스터는 여기서 바로 사용하고, 쪽지권·프로필 변경권은 해당 기능 이용 시 자동으로 사용됩니다.
				</p>

				<div className='text-sm text-neutral-500 mb-3'>미사용 {total.toLocaleString()}개</div>

				{loading ? (
					<Loading />
				) : items.length === 0 ? (
					<div className='text-center py-20 text-neutral-500'>보유한 아이템이 없습니다.</div>
				) : (
					<>
						<ul className='flex flex-col gap-3'>
							{items.map((item) => {
								const directUse = DIRECT_USE_KINDS.includes(item.kind);

								return (
									<li
										key={item.id}
										className='flex items-center gap-4 rounded-lg border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 p-4'
									>
										<div className='size-14 shrink-0 rounded bg-neutral-100 dark:bg-neutral-800 overflow-hidden flex items-center justify-center'>
											{item.thumbnail ? (
												// eslint-disable-next-line @next/next/no-img-element
												<img src={item.thumbnail} alt={item.productName} className='w-full h-full object-scale-down' />
											) : (
												<span className='text-2xl'>🎁</span>
											)}
										</div>

										<div className='flex-1 min-w-0'>
											<div className='font-semibold truncate'>
												{ITEM_KIND_LABEL[item.kind] ?? item.productName}
												{item.kind === 'ExpBooster' && item.durationDays > 0 && (
													<span className='ml-1 text-xs text-neutral-500'>({item.durationDays}일)</span>
												)}
											</div>
											<div className='text-xs text-neutral-500 line-clamp-2'>{ITEM_KIND_DESC[item.kind]}</div>
										</div>

										<div className='shrink-0'>
											{directUse ? (
												<button
													type='button'
													onClick={() => useItem(item)}
													disabled={busyID === item.id}
													className='px-4 py-2 rounded-md bg-red-600 text-white text-sm font-semibold hover:bg-red-700 disabled:opacity-50'
												>
													{busyID === item.id ? '처리 중...' : '사용하기'}
												</button>
											) : (
												<span className='text-xs text-neutral-400'>기능 이용 시 사용</span>
											)}
										</div>
									</li>
								);
							})}
						</ul>

						<hr className='my-4 border-neutral-200 dark:border-neutral-800' />

						<Pagination total={total} page={page} perPage={PER_PAGE} onChange={setPage} />
					</>
				)}
			</div>
		</>
	);
}