import { useDatabase } from "@/app/providers/DatabaseProvider/useDatabase";
import { useRosettaColors } from "@/app/hooks/useRosettaColors";
import { useViewPanelsState, ViewPanelsState } from "@/app/hooks/useViewPanelsState";
import { usePublicKey } from "@/app/providers/AccountProvider/usePublicKey";
import { useDialogsList } from "@/app/providers/DialogListProvider/useDialogsList";
import { Badge, Flex } from "@mantine/core";
import { IconChevronLeft } from "@tabler/icons-react";
import { useEffect, useState } from "react";

export function BackToDialogs() {
    const colors = useRosettaColors();
    const [unreadedMessagessCount, setUnreadedMessagesCount] = useState(0);
    const {dialogs} = useDialogsList();
    const [_, setViewState] = useViewPanelsState();
    const {getQuery} = useDatabase();
    const publicKey = usePublicKey();
    
    useEffect(() => {
        (async () => {
            const result = await getQuery(`
                SELECT COUNT(*) AS unloaded_count FROM messages WHERE from_me = 0 AND read = 0 AND account = ?
                `, [publicKey]);
            setUnreadedMessagesCount(result.unloaded_count || 0);
        })();
    }, [dialogs, publicKey]);

    const onClickDialogs = () => {
        setViewState(ViewPanelsState.DIALOGS_PANEL_ONLY);
    }

    return (
        <>
            <Flex align={'center'} justify={'flex-start'} style={{cursor: 'pointer', position: 'relative'}} onClick={onClickDialogs}>
                <IconChevronLeft color={colors.brandColor}>
                </IconChevronLeft>
                {unreadedMessagessCount > 0 && 
                    <Badge style={{
                    cursor: 'pointer',
                    position: 'absolute',
                    top: -8,
                    left: 15,
                    minWidth: 10,
                    zIndex: 10
                    }} color="var(--mantine-color-red-5)" variant="filled" circle size={'sm'}>
                        {unreadedMessagessCount > 9 ? '9+' : unreadedMessagessCount}
                    </Badge>
                }
            </Flex>
        </>
    );
}