"use client";

import { createContext, useContext, useState, ReactNode, useEffect } from 'react';

interface Customer {
    id: string;
    name: string;
    email: string;
    company: string;
    logo_url?: string;
}

interface CRMFilterContextType {
    selectedCustomerId: string | null;
    setSelectedCustomerId: (id: string | null) => void;
    customers: Customer[];
    setCustomers: (customers: Customer[]) => void;
    loading: boolean;
    setLoading: (loading: boolean) => void;
}

const CRMFilterContext = createContext<CRMFilterContextType | undefined>(undefined);

export function CRMFilterProvider({ children }: { children: ReactNode }) {
    const [selectedCustomerId, setSelectedCustomerId] = useState<string | null>(null);
    const [customers, setCustomers] = useState<Customer[]>([]);
    const [loading, setLoading] = useState(false);

    return (
        <CRMFilterContext.Provider
            value={{
                selectedCustomerId,
                setSelectedCustomerId,
                customers,
                setCustomers,
                loading,
                setLoading
            }}
        >
            {children}
        </CRMFilterContext.Provider>
    );
}

export function useCRMFilter() {
    const context = useContext(CRMFilterContext);
    if (context === undefined) {
        throw new Error('useCRMFilter must be used within a CRMFilterProvider');
    }
    return context;
}
