"use client"

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

interface TrimContextType {
    trim: ReactElement | null;
    setTrim: (content: ReactElement | null) => void;
}

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

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

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

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

    return (
        <TrimContext.Provider value={{ trim, setTrim }}>
            {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;
};
