import { useForm } from "@mantine/form";
import { useEffect, useState } from "react";
import { BaseMarketplaceSchema } from "../../../../../client";
import { useCardSummariesFull } from "../../../hooks/useCardSummaries.tsx";
import isModuleInProject, { Modules } from "../../../../../modules/utils/isModuleInProject.ts";

type State = {
    idOrName: string | null;
    marketplace: BaseMarketplaceSchema | null;
};

const usePrefillCard = () => {
    const { objects } = useCardSummariesFull();
    const form = useForm<State>({
        initialValues: {
            idOrName: null,
            marketplace: null,
        },
    });
    const [data, setData] = useState(objects);

    const applyFilters = () => {
        let result = objects;

        result = result.filter(obj => isModuleInProject(Modules.SERVICES_AND_PRODUCTS, obj.board.project));

        if (form.values.idOrName) {
            if (isNaN(parseInt(form.values.idOrName))) {
                const name: string = form.values.idOrName.toLowerCase();
                result = result.filter(
                    obj => obj.name.toLowerCase().search(name) !== -1,
                );
            } else {
                const id = parseInt(form.values.idOrName);
                result = result.filter(
                    obj => obj.id === id,
                );
            }
        }
        if (form.values.marketplace) {
            result = result.filter(
                obj => obj.baseMarketplace?.key === form.values.marketplace?.key,
            );
        }
        setData(result);
    };

    useEffect(() => {
        applyFilters();
    }, [form.values, objects]);

    return { data, form };
};

export default usePrefillCard;
