"use client";

import { IconEdit, IconFilter, IconPlus } from "@tabler/icons-react";
import { Flex, Group } from "@mantine/core";
import { modals } from "@mantine/modals";
import ToolPanelAction from "@/app/deals/components/desktop/ToolPanelAction/ToolPanelAction";
import ViewSelector from "@/app/deals/components/desktop/ViewSelector/ViewSelector";
import { useDealsContext } from "@/app/deals/contexts/DealsContext";
import { useProjectsContext } from "@/app/deals/contexts/ProjectsContext";
import { useViewContext } from "@/app/deals/contexts/ViewContext";
import DealsTableFiltersModal from "@/app/deals/modals/DealsTableFiltersModal/DealsTableFiltersModal";
import ProjectSelect from "@/components/selects/ProjectSelect/ProjectSelect";
import { useDrawersContext } from "@/drawers/DrawersContext";
import useIsMobile from "@/hooks/utils/useIsMobile";

const TopToolPanel = () => {
    const { dealsFilters } = useDealsContext();
    const { view } = useViewContext();
    const { projects, setSelectedProjectId, selectedProject, projectsCrud } =
        useProjectsContext();
    const { openDrawer } = useDrawersContext();
    const isMobile = useIsMobile();

    if (isMobile) return;

    const onCreateClick = () => {
        modals.openContextModal({
            modal: "enterNameModal",
            title: "Создание проекта",
            withCloseButton: true,
            innerProps: {
                onComplete: projectsCrud.onCreate,
            },
        });
    };

    const onEditClick = () => {
        if (!selectedProject) return;

        openDrawer({
            key: "selectedProjectEditorDrawer",
            props: { project: selectedProject, projectsCrud },
        });
    };

    return (
        <Group justify={"space-between"}>
            <ViewSelector />
            <Flex
                wrap={"nowrap"}
                align={"center"}
                gap={"sm"}>
                <DealsTableFiltersModal
                    getOpener={onFiltersClick => (
                        <ToolPanelAction onClick={onFiltersClick}>
                            <IconFilter />
                        </ToolPanelAction>
                    )}
                    filters={dealsFilters}
                    selectedProject={selectedProject}
                    boardAndStatusEnabled={view === "table"}
                />
                <ToolPanelAction onClick={onEditClick}>
                    <IconEdit />
                </ToolPanelAction>
                <ToolPanelAction onClick={onCreateClick}>
                    <IconPlus />
                </ToolPanelAction>
                <ProjectSelect
                    data={projects}
                    value={selectedProject}
                    onChange={value => value && setSelectedProjectId(value.id)}
                    style={{ width: 250 }}
                />
            </Flex>
        </Group>
    );
};

export default TopToolPanel;
