"use client"

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

interface BodyTypeContextType {
    bodyType: ReactElement | null;
    setBodyType: (content: ReactElement | null) => void;
}

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

export const BodyTypeProvider = ({ children }: { children: ReactNode }) => {
    const [bodyType, setBodyType] = useState<any | null>(null);

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

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

    return (
        <BodyTypeContext.Provider value={{ bodyType, setBodyType }}>
            {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;
};
