import { useEffect, useState } from "react";
import { useDebouncedValue } from "@mantine/hooks";
import { ClientSchema } from "@/lib/client";

type Props = {
    clients: ClientSchema[];
};

const useClientsFilter = ({ clients }: Props) => {
    const [search, setSearch] = useState<string>("");
    const [debouncedSearch] = useDebouncedValue(search, 400);
    const [filteredClients, setFilteredClients] = useState<ClientSchema[]>([]);

    const filterClients = () => {
        if (debouncedSearch.length === 0) {
            setFilteredClients(clients);
            return;
        }

        const loweredSearch = debouncedSearch.toLowerCase();
        const filtered = clients.filter(
            client =>
                client.name.toLowerCase().includes(loweredSearch) ||
                client.details?.inn?.includes(loweredSearch) ||
                client.details?.email?.toLowerCase().includes(loweredSearch) ||
                client.details?.telegram
                    ?.toLowerCase()
                    .includes(loweredSearch) ||
                client.details?.phoneNumber?.includes(loweredSearch) ||
                client.companyName.toLowerCase().includes(loweredSearch)
        );
        setFilteredClients(filtered);
    };

    useEffect(() => {
        filterClients();
    }, [debouncedSearch, clients]);

    return {
        search,
        setSearch,
        filteredClients,
    };
};

export default useClientsFilter;
