"use client";

import { IconChevronLeft, IconSettings } from "@tabler/icons-react";
import { Box, Group, Stack, Text } from "@mantine/core";
import Boards from "@/app/deals/components/shared/Boards/Boards";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import { useProjectsContext } from "@/app/deals/contexts/ProjectsContext";
import { useDrawersContext } from "@/drawers/DrawersContext";
import useIsMobile from "@/hooks/utils/useIsMobile";

const MainBlockHeader = () => {
    const { setSelectedProjectId, refetchProjects, selectedProject } =
        useProjectsContext();
    const { refetchBoards } = useBoardsContext();
    const { openDrawer } = useDrawersContext();
    const isMobile = useIsMobile();

    const selectProjectId = async (projectId: number | null) => {
        await refetchProjects();
        setSelectedProjectId(projectId);
    };

    const openProjectsEditorDrawer = () => {
        openDrawer({
            key: "projectsMobileEditorDrawer",
            props: {
                onSelect: project => selectProjectId(project?.id ?? null),
            },
        });
    };

    const openBoardsEditorDrawer = () => {
        if (!selectedProject) return;
        openDrawer({
            key: "boardsMobileEditorDrawer",
            props: {
                project: selectedProject,
            },
            onClose: refetchBoards,
        });
    };

    return (
        <Stack
            gap={0}
            w={"100%"}>
            {isMobile && (
                <Group justify={"space-between"}>
                    <Box
                        p={"md"}
                        onClick={openProjectsEditorDrawer}>
                        <IconChevronLeft />
                    </Box>
                    <Text>{selectedProject?.name}</Text>
                    <Box
                        p={"md"}
                        onClick={openBoardsEditorDrawer}>
                        <IconSettings />
                    </Box>
                </Group>
            )}
            <Group
                wrap={"nowrap"}
                gap={0}
                align={"end"}>
                <Boards />
                <Box
                    flex={1}
                    style={{ borderBottom: "2px solid gray" }}
                />
            </Group>
        </Stack>
    );
};

export default MainBlockHeader;
