"use client"

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

interface CarBrandContextType {
    carBrand: ReactElement | null;
    setCarBrand: (content: ReactElement | null) => void;
}

const CarBrandContext = createContext<CarBrandContextType | undefined>(undefined);

export const CarBrandProvider = ({ children }: { children: ReactNode }) => {
    const [carBrand, setCarBrand] = useState<any | null>(null);

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

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

    return (
        <CarBrandContext.Provider value={{ carBrand, setCarBrand }}>
            {children}
        </CarBrandContext.Provider>
    );
};

export const useCarBrandContext = (): CarBrandContextType => {
    const context = useContext(CarBrandContext);
    if (!context) {
        throw new Error('useCarBrandContext must be used within a CarBrandProvider');
    }
    return context;
};