'use client';

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

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

	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/goal/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>
			<GoalListPanel
				items={items}
				loading={loading}
				saving={saving}
				checkedIDs={checkedIDs}
				setCheckedIDs={setCheckedIDs}
				page={page}
				setPage={setPage}
				perPage={perPage}
				setPerPage={setPerPage}
				onNew={() => router.push('/studio/donation/goal/add')}
				onEdit={(item) => router.push(`/studio/donation/goal/edit/${item.id}`)}
				onBatchDelete={handleBatchDelete}
			/>
		</>
	);
}