"use client"

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

export interface BodyTypeItem {
    id: string;
    name: string;
}

interface BodyTypeContextType {
    bodyTypes: BodyTypeItem[] | null;
    setBodyTypes: (content: BodyTypeItem[] | null) => void;
    fetchData: () => void;
}

const BodyTypeContext = createContext<BodyTypeContextType | undefined>(undefined);

export const BodyTypeProvider = ({ children }: { children: ReactNode }) => {
    const [bodyTypes, setBodyTypes] = useState<BodyTypeItem[] | null>(null);

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

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

    return (
        <BodyTypeContext.Provider value={{ bodyTypes, setBodyTypes, fetchData }}>
            {children}
        </BodyTypeContext.Provider>
    );
};

export const useBodyTypeContext = (): BodyTypeContextType => {
    const context = useContext(BodyTypeContext);
    if (!context) {
        throw new Error('useBodyTypeContext must be used within a BodyTypeProvider');
    }
    return context;
};
