'use client';

import './style.scss';
import { useState, useCallback, useEffect } from 'react';
import { fetchApi } from '@/lib/utils/client';
import { useStudioContext } from '@/app/studio/context';
import type { AlertConfigResponse, AlertConfigItem } from '@/types/response/donation/alertConfig';
import { AlertConfigContext } from './context';

export default function AlertLayout({ children }: { children: React.ReactNode })
{
	const { channelID } = useStudioContext();

	const [items, setItems] = useState<AlertConfigItem[]>([]);
	const [widgetToken, setWidgetToken] = useState<string|null>(null);
	const [loading, setLoading] = useState(true);
	const [saving, setSaving] = useState(false);

	const fetchList = useCallback(() => {
		if (!channelID) {
			setLoading(false);
			return;
		}

		setLoading(true);

		fetchApi<AlertConfigResponse>(`/api/studio/donation/alert/config/${channelID}`).then(res => {
			setItems(res.data?.list ?? []);
			setWidgetToken(res.data?.widgetToken ?? null);
		}).catch(err => {
			alert(err instanceof Error ? err.message : '불러오기 실패');
		}).finally(() => setLoading(false));

	}, [channelID]);

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

	if (!channelID) {
		return (
			<div className="studio-page">
				<p className="studio-page__empty">채널을 먼저 연동해 주세요.</p>
			</div>
		);
	}

	return (
		<AlertConfigContext.Provider value={{ items, widgetToken, loading, saving, setSaving, fetchList }}>
			<div className="alert-config">
				{children}
			</div>
		</AlertConfigContext.Provider>
	);
}