'use client';

import './style.scss';
import { useState, useEffect, useCallback, type ReactNode } from 'react';
import { fetchApi } from '@/lib/utils/client';
import { useStudioContext } from '@/app/studio/context';
import type { CrewWidgetConfigResponse, CrewWidgetConfigItem } from '@/types/response/crew/widgetConfig';
import { CrewWidgetConfigContext } from './context';

export default function CrewWidgetLayout({ children }: { children: ReactNode })
{
	const { channelID } = useStudioContext();
	const [items, setItems] = useState<CrewWidgetConfigItem[]>([]);
	const [loading, setLoading] = useState(true);
	const [saving, setSaving] = useState(false);

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

		setLoading(true);

		fetchApi<CrewWidgetConfigResponse>(`/api/studio/crew/widget/config/${channelID}`)
			.then(res => setItems(res.data?.list ?? []))
			.catch(() => {})
			.finally(() => setLoading(false)
		);

	}, [channelID]);

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

	return (
		<CrewWidgetConfigContext.Provider value={{ items, loading, saving, setSaving, fetchList }}>
			{children}
		</CrewWidgetConfigContext.Provider>
	);
}