"use client"

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

export interface EngineItem {
    id: string,
    type: string,
    powerHR: string,
    volume: string,
}

interface EngineContextType {
    engine: EngineItem[] | null;
    setEngine: (content: EngineItem[] | null) => void;
    fetchData: () => void;
}

const EngineContext = createContext<EngineContextType | undefined>(undefined);

export const EngineProvider = ({ children }: { children: ReactNode }) => {
    const [engine, setEngine] = useState<EngineItem[] | null>(null);

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

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

    return (
        <EngineContext.Provider value={{ engine, setEngine, fetchData }}>
            {children}
        </EngineContext.Provider>
    );
};

export const useEngineContext = (): EngineContextType => {
    const context = useContext(EngineContext);
    if (!context) {
        throw new Error('useEngineContext must be used within an EngineProvider');
    }
    return context;
};
