"use client"

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

export interface CarModelItem {
    id: string;
    name: string;
    yearStart: string,
    yearEnd: string,
    car_brands_id: string,
}

interface CarModelContextType {
    carModel: CarModelItem[] | null;
    setCarModel: (content: CarModelItem[] | null) => void;
    fetchData: () => void;
}

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

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

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

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

    return (
        <CarModelContext.Provider value={{ carModel, setCarModel, fetchData }}>
            {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;
};
