"use client"

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

export interface TrimItem {
    id: string;
    name: string,
    price: string,
    car_models_id: string,
}

interface TrimContextType {
    trim: TrimItem[] | null;
    setTrim: (content: TrimItem[] | null) => void;
    fetchData: () => void;
}

const TrimContext = createContext<TrimContextType | undefined>(undefined);

export const TrimProvider = ({ children }: { children: ReactNode }) => {
    const [trim, setTrim] = useState<TrimItem[] | null>(null);

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

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

    return (
        <TrimContext.Provider value={{ trim, setTrim, fetchData }}>
            {children}
        </TrimContext.Provider>
    );
};

export const useTrimContext = (): TrimContextType => {
    const context = useContext(TrimContext);
    if (!context) {
        throw new Error('useTrimContext must be used within a TrimProvider');
    }
    return context;
};
