"use client"

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

export interface CustomerItem {
    id: string;
    name: string;
    phone: string;
    email: string;
}

interface CustomerContextType {
    customers: CustomerItem[] | [];
    setCustomers: (content: CustomerItem[] | []) => void;
    fetchData: () => void;
}

const CustomerContext = createContext<CustomerContextType | undefined>(undefined);

export const CustomerProvider = ({ children }: { children: ReactNode }) => {
    const [customers, setCustomers] = useState<CustomerItem[] | []>([]);

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

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

    return (
        <CustomerContext.Provider value={{ customers, setCustomers, fetchData }}>
            {children}
        </CustomerContext.Provider>
    );
};

export const useCustomerContext = (): CustomerContextType => {
    const context = useContext(CustomerContext);
    if (!context) {
        throw new Error('useCustomerContext must be used within a CustomerProvider');
    }
    return context;
};
