'use client';

import { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { BroadcastInfo, BroadcastState } from '@/types/broadcast';
import { liveStreams, generateNewBroadcast, getTopPopularStreams } from '@/data/mockBroadcasts';

// 방송 정보 Context 타입
interface BroadcastContextType {
    // 상태
    popularBroadcasts: BroadcastInfo[];
    liveBroadcasts: BroadcastInfo[];
    isLoading: boolean;
    error: string | null;
    currentPage: number;
    hasMore: boolean;

    // 액션
    fetchPopularBroadcasts: () => void;
    fetchLiveBroadcasts: () => void;
    loadMoreBroadcasts: () => void;
    refreshBroadcasts: () => void;
    updateBroadcast: (broadcast: BroadcastInfo) => void;
    removeBroadcast: (broadcastId: string) => void;
}

// Context 생성
const BroadcastContext = createContext<BroadcastContextType>({
    popularBroadcasts: [],
    liveBroadcasts: [],
    isLoading: false,
    error: null,
    currentPage: 1,
    hasMore: true,
    fetchPopularBroadcasts: () => {},
    fetchLiveBroadcasts: () => {},
    loadMoreBroadcasts: () => {},
    refreshBroadcasts: () => {},
    updateBroadcast: () => {},
    removeBroadcast: () => {},
});

// Context Provider
export function BroadcastProvider({ children }: { children: React.ReactNode }) {
    const [state, setState] = useState<BroadcastState>({
        popularBroadcasts: [],
        liveBroadcasts: [],
        isLoading: false,
        error: null,
        currentPage: 1,
        hasMore: true,
    });

    // 인기 방송 목록 로드
    const fetchPopularBroadcasts = useCallback(() => {
        setState(prev => ({ ...prev, isLoading: true, error: null }));

        // 실시간 LIVE에서 시청자수 기준 top5 가져오기
        setState(prev => ({
            ...prev,
            popularBroadcasts: getTopPopularStreams(5),
            isLoading: false,
        }));
    }, []);

    // 실시간 방송 목록 로드
    const fetchLiveBroadcasts = useCallback(() => {
        setState(prev => ({ ...prev, isLoading: true, error: null }));

        // 더미 데이터에서 실시간 방송 목록 가져오기
        setState(prev => ({
            ...prev,
            liveBroadcasts: [...liveStreams],
            isLoading: false,
        }));
    }, []);

    // 더 많은 방송 로드 (무한스크롤용)
    const loadMoreBroadcasts = useCallback(() => {
        if (!state.hasMore || state.isLoading) return;

        setState(prev => ({ ...prev, isLoading: true }));

        // 헬퍼 함수를 사용하여 새로운 방송 생성
        const newBroadcast = generateNewBroadcast(state.currentPage + 1);

        setState(prev => ({
            ...prev,
            liveBroadcasts: [...prev.liveBroadcasts, newBroadcast],
            currentPage: prev.currentPage + 1,
            hasMore: prev.currentPage < 5,
            isLoading: false,
        }));
    }, [state.hasMore, state.isLoading, state.currentPage]);

    // 방송 목록 새로고침
    const refreshBroadcasts = useCallback(() => {
        setState(prev => ({ ...prev, currentPage: 1, hasMore: true }));
        fetchPopularBroadcasts();
        fetchLiveBroadcasts();
    }, [fetchPopularBroadcasts, fetchLiveBroadcasts]);

    // 방송 정보 업데이트
    const updateBroadcast = useCallback((updatedBroadcast: BroadcastInfo) => {
        setState(prev => ({
            ...prev,
            popularBroadcasts: prev.popularBroadcasts.map(broadcast =>
                broadcast.id === updatedBroadcast.id ? updatedBroadcast : broadcast
            ),
            liveBroadcasts: prev.liveBroadcasts.map(broadcast =>
                broadcast.id === updatedBroadcast.id ? updatedBroadcast : broadcast
            ),
        }));
    }, []);

    // 방송 제거
    const removeBroadcast = useCallback((broadcastId: string) => {
        setState(prev => ({
            ...prev,
            popularBroadcasts: prev.popularBroadcasts.filter(broadcast => broadcast.id !== broadcastId),
            liveBroadcasts: prev.liveBroadcasts.filter(broadcast => broadcast.id !== broadcastId),
        }));
    }, []);

    // 초기 데이터 로드
    useEffect(() => {
        fetchPopularBroadcasts();
        fetchLiveBroadcasts();
    }, [fetchPopularBroadcasts, fetchLiveBroadcasts]);

    const value: BroadcastContextType = {
        ...state,
        fetchPopularBroadcasts,
        fetchLiveBroadcasts,
        loadMoreBroadcasts,
        refreshBroadcasts,
        updateBroadcast,
        removeBroadcast,
    };

    return (
        <BroadcastContext.Provider value={value}>
            {children}
        </BroadcastContext.Provider>
    );
}

// Context 사용을 위한 커스텀 훅
export function useBroadcastContext() {
    const context = useContext(BroadcastContext);
    if (!context) {
        throw new Error('useBroadcastContext must be used within a BroadcastProvider');
    }
    return context;
}