"use client"

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

export interface CarItem {
    id: string,
    car_models_id: string,
    engines_id: string,
    trims_id: string,
    body_types_id: string,
    car_colors_id: string,
    transmissions_id: string,
}

interface CarContextType {
    car: CarItem[] | null;
    setCar: (content: CarItem[] | null) => void;
    fetchData: () => void;
}

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

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

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

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

    return (
        <CarContext.Provider value={{ car, setCar, fetchData }}>
            {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;
};
