'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { fetchApi } from '@/lib/utils/client';
import { useStudioContext } from '@/app/studio/context';
import { useRankConfigContext } from '../context';
import RankListPanel from '../_components/RankListPanel';
import { DEFAULT_PER_PAGE } from '@/constants/donation';

export default function RankListPage()
{
	const router = useRouter();
	const { channelID } = useStudioContext();
	const { items, loading, saving, setSaving, fetchList } = useRankConfigContext();

	const [checkedIDs, setCheckedIDs] = useState<Set<number>>(new Set());
	const [page, setPage] = useState(1);
	const [perPage, setPerPage] = useState(DEFAULT_PER_PAGE);

	const handleBatchDelete = async () => {
		if (!channelID || checkedIDs.size === 0) {
			return;
		}
		if (!confirm(`선택한 ${checkedIDs.size}개의 순위 설정을 삭제하시겠습니까?`)) {
			return;
		}

		setSaving(true);

		try {
			const deletePromises = [...checkedIDs].map(id =>
				fetchApi(`/api/studio/donation/rank/config/${id}/${channelID}`, { method: 'DELETE' })
			);

			await Promise.all(deletePromises);
			setCheckedIDs(new Set());
			fetchList();
		} catch (err) {
			alert(err instanceof Error ? err.message : '삭제에 실패했습니다.');
		} finally {
			setSaving(false);
		}
	};

	return (
		<>
			<h1 className="studio-page__title">후원 순위</h1>
			<div>
				<br/>
			</div>
			<RankListPanel
				items={items}
				loading={loading}
				saving={saving}
				checkedIDs={checkedIDs}
				setCheckedIDs={setCheckedIDs}
				page={page}
				setPage={setPage}
				perPage={perPage}
				setPerPage={setPerPage}
				onNew={() => router.push('/studio/donation/rank/add')}
				onEdit={(item) => router.push(`/studio/donation/rank/edit/${item.id}`)}
				onBatchDelete={handleBatchDelete}
			/>
		</>
	);
}