"use client"

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { ReactElement } from 'react';
import { list } from "@/api/sales"; // Assuming your API call for sales is here

interface SaleContextType {
    sale: ReactElement | null;
    setSale: (content: ReactElement | null) => void;
}

const SaleContext = createContext<SaleContextType | undefined>(undefined);

export const SaleProvider = ({ children }: { children: ReactNode }) => {
    const [sale, setSale] = useState<any | null>(null);

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

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

    return (
        <SaleContext.Provider value={{ sale, setSale }}>
            {children}
        </SaleContext.Provider>
    );
};

export const useSaleContext = (): SaleContextType => {
    const context = useContext(SaleContext);
    if (!context) {
        throw new Error('useSaleContext must be used within a SaleProvider');
    }
    return context;
};
