import { useForm } from "@mantine/form";
import { useEffect, useState } from "react";
import { BaseMarketplaceSchema } from "../../../../../client";
import { useDealSummariesFull } from "../../../hooks/useDealSummaries.tsx";

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

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

    const applyFilters = () => {
        let result = objects;
        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 usePrefillDeal;
