'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 { RankConfigResponse, RankConfigItem } from '@/types/response/donation/rankConfig';
import { RankConfigContext } from './context';

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

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

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

		setLoading(true);

		fetchApi<RankConfigResponse>(`/api/studio/donation/rank/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 (
		<RankConfigContext.Provider value={{ items, loading, saving, setSaving, fetchList }}>
			<div className="rank-config">
				{children}
			</div>
		</RankConfigContext.Provider>
	);
}