"use client"

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

interface CarModelContextType {
    carModel: ReactElement | null;
    setCarModel: (content: ReactElement | null) => void;
}

const CarModelContext = createContext<CarModelContextType | undefined>(undefined);

export const CarModelProvider = ({ children }: { children: ReactNode }) => {
    const [carModel, setCarModel] = useState<any | null>(null);

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

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

    return (
        <CarModelContext.Provider value={{ carModel, setCarModel }}>
            {children}
        </CarModelContext.Provider>
    );
};

export const useCarModelContext = (): CarModelContextType => {
    const context = useContext(CarModelContext);
    if (!context) {
        throw new Error('useCarModelContext must be used within a CarModelProvider');
    }
    return context;
};
