"use client";

import { Dispatch, SetStateAction } from "react";
import {
    ClientsCrud,
    useClientsCrud,
} from "@/app/clients/hooks/useClientsCrud";
import useClientsFilter from "@/app/clients/hooks/useClientsFilter";
import useClientsList from "@/app/clients/hooks/useClientsList";
import { ClientSchema } from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";

type ClientsContextState = {
    clients: ClientSchema[];
    refetchClients: () => void;
    search: string;
    setSearch: Dispatch<SetStateAction<string>>;
    clientsCrud: ClientsCrud;
};

const useClientsContextState = (): ClientsContextState => {
    const clientsList = useClientsList();

    const { filteredClients, search, setSearch } =
        useClientsFilter(clientsList);

    const clientsCrud = useClientsCrud(clientsList);

    return {
        clients: filteredClients,
        refetchClients: clientsList.refetch,
        search,
        setSearch,
        clientsCrud,
    };
};

export const [ClientsContextProvider, useClientsContext] =
    makeContext<ClientsContextState>(useClientsContextState, "Clients");
