'use client';

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

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

	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 {

			await fetchApi('/api/studio/donation/alert/config/batch', {
				method: 'POST',
				body: {
					channelID,
					memberID,
					items: [],
					deleteIDs: [...checkedIDs]
				}
			});

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