"use client"

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

interface CarContextType {
    car: ReactElement | null;
    setCar: (content: ReactElement | null) => void;
}

const CarContext = createContext<CarContextType | undefined>(undefined);

export const CarProvider = ({ children }: { children: ReactNode }) => {
    const [car, setCar] = useState<any | null>(null);

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

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

    return (
        <CarContext.Provider value={{ car, setCar }}>
            {children}
        </CarContext.Provider>
    );
};

export const useCarContext = (): CarContextType => {
    const context = useContext(CarContext);
    if (!context) {
        throw new Error('useCarContext must be used within a CarProvider');
    }
    return context;
};
