'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 { GoalConfigResponse, GoalConfigItem } from '@/types/response/donation/goalConfig';
import { GoalConfigContext } from './context';

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

	const [items, setItems] = useState<GoalConfigItem[]>([]);
	const [loading, setLoading] = useState(true);
	const [saving, setSaving] = useState(false);

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

		setLoading(true);

		fetchApi<GoalConfigResponse>(`/api/studio/donation/goal/config/${channelID}`).then(res => {
			setItems(res.data?.list ?? []);
		}).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 (
		<GoalConfigContext.Provider value={{ items, loading, saving, setSaving, fetchList }}>
			<div className="goal-config">
				{children}
			</div>
		</GoalConfigContext.Provider>
	);
}