"use client"

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

export interface CarBrandItem {
    id: string;
    name: string;
    country: string;
}

interface CarBrandContextType {
    carBrands: CarBrandItem[] | null;
    setCarBrands: (content: CarBrandItem[] | null) => void;
    fetchData: () => void;
}

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

export const CarBrandProvider = ({ children }: { children: ReactNode }) => {
    const [carBrands, setCarBrands] = useState<CarBrandItem[] | null>(null);

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

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

    return (
        <CarBrandContext.Provider value={{ carBrands, setCarBrands, fetchData }}>
            {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;
};