"use client";

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

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");
