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


type Props = {
    projects: ProjectSchema[];
}

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

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

const useCardsPageState = ({ projects }: Props) => {
    const { objects } = useCardSummariesFull();

    const form = useForm<CardsPageState>({
        initialValues: {
            project: null,
            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.project?.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]);

    useEffect(() => {
        if (projects.length > 0 && form.values.project === null) {
            form.setFieldValue("project", projects[0]);
        }
    }, [projects]);

    return { data, form };
};

export default useCardsPageState;
