"use client"

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

export interface SaleItem {
    id: string,
    date: string,
    price: string,
    cars_id: string,
    customers_id: string,
}

interface SaleContextType {
    sale: SaleItem[] | null;
    setSale: (content: SaleItem[] | null) => void;
    fetchData: () => void;
}

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

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

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

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

    return (
        <SaleContext.Provider value={{ sale, setSale, fetchData }}>
            {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;
};
