import { useCardSummariesFull } from "./useCardSummaries.tsx";
import { useForm } from "@mantine/form";
import { useEffect, useState } from "react";
import { BaseMarketplaceSchema, BoardSchema, ClientSchema, ProjectSchema, StatusSchema } from "../../../client";

export type CardsPageState = {
    id: number | null;
    marketplace: BaseMarketplaceSchema | null;
    client: ClientSchema | null;

    projectForTable: ProjectSchema | null;
    board: BoardSchema | null;
    status: StatusSchema | null;
};

const useCardsPageState = () => {
    const { objects } = useCardSummariesFull();

    const form = useForm<CardsPageState>({
        initialValues: {
            id: null,
            marketplace: null,
            client: null,

            projectForTable: null,
            board: null,
            status: null,
        },
    });

    const [data, setData] = useState(objects);

    const applyFilters = () => {
        let result = objects;
        if (form.values.id) {
            result = result.filter(
                obj => obj.id === form.values.id,
            );
        }
        if (form.values.marketplace) {
            result = result.filter(
                obj => obj.baseMarketplace?.key === form.values.marketplace?.key,
            );
        }
        if (form.values.projectForTable) {
            result = result.filter(
                obj => obj.board.projectId === form.values.projectForTable?.id,
            );

            if (form.values.board) {
                result = result.filter(
                    obj => obj.board.id === form.values.board?.id,
                );

                if (form.values.status) {
                    result = result.filter(
                        obj => obj.status.id === form.values.status?.id,
                    );
                }
            }
        }
        if (form.values.client) {
            result = result.filter(
                obj => obj.clientName === form.values.client?.name,
            );
        }
        setData(result);
    };

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

    return { data, form };
};

export default useCardsPageState;
