"use client"

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { list } from "@/api/transmissions";

export interface TransmissionItem {
    id: string,
    type: string,
}

interface TransmissionContextType {
    transmission: TransmissionItem[] | null;
    setTransmission: (content: TransmissionItem[] | null) => void;
    fetchData: () => void;
}

const TransmissionContext = createContext<TransmissionContextType | undefined>(undefined);

export const TransmissionProvider = ({ children }: { children: ReactNode }) => {
    const [transmission, setTransmission] = useState<TransmissionItem[] | null>(null);

    const fetchData = async () => {
        setTransmission(await list());
    };

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

    return (
        <TransmissionContext.Provider value={{ transmission, setTransmission, fetchData }}>
            {children}
        </TransmissionContext.Provider>
    );
};

export const useTransmissionContext = (): TransmissionContextType => {
    const context = useContext(TransmissionContext);
    if (!context) {
        throw new Error('useTransmissionContext must be used within a TransmissionProvider');
    }
    return context;
};
