import { Box, Divider, Flex, ScrollArea } from '@mantine/core';
import { RequestsButton } from '../RequestsButton/RequestsButton';
import { UserButton } from '../UserButton/UserButton';
import { useEffect, useState } from 'react';
import { useRosettaColors } from '@/app/hooks/useRosettaColors';
import { UpdateAlert } from '../UpdateAlert/UpdateAlert';
import { useNavigate } from 'react-router-dom';
import { DialogsList } from '../DialogsList/DialogsList';
import { DialogsPanelHeader } from '../DialogsPanelHeader/DialogsPanelHeader';
import { useDialogsList } from '@/app/providers/DialogListProvider/useDialogsList';

export function DialogsPanel() {
    const [dialogsMode, setDialogsMode] = useState<'all' | 'requests'>('all');
    const [requestsCount, setRequestsCount] = useState(0);
    const {dialogs} = useDialogsList();
    const colors = useRosettaColors();
    const navigate = useNavigate();

    useEffect(() => {
        ((async () => {
            let requests = dialogs.filter(d => d.is_request);
            setRequestsCount(requests.length);
            if(requests.length == 0 && dialogsMode == 'requests'){
                setDialogsMode('all');
            }
        }))();
    }, [dialogs]);

    const changeDialogMode = () => {
        if(dialogsMode == 'all'){
            setDialogsMode('requests');
        } else {
            setDialogsMode('all');
        }
    }

    const onSelectDialog = async (dialog: string) => {
        console.info("[PT] SELECT DIALOG ", Date.now());
        navigate(`/main/chat/${dialog.replace("#", "%23")}`);
    }

    return (
        <Flex
            style={{
                minWidth: 300,
                minHeight: 'calc(100vh - 30px)',
                maxHeight: 'calc(100vh - 30px)'
            }}
            direction={'column'}
            justify={'space-between'}
        >
            <Box>
                <DialogsPanelHeader></DialogsPanelHeader>
                {requestsCount > 0 && <RequestsButton mode={dialogsMode} onClick={changeDialogMode} count={requestsCount}></RequestsButton>}
                <Divider color={colors.borderColor}></Divider>
            </Box>
            <ScrollArea.Autosize scrollbarSize={5} style={{
                flexGrow: 1,
                display: 'flex'
            }}>
                <Flex direction={'column'}>
                    <DialogsList onSelectDialog={onSelectDialog} mode={dialogsMode}>
                    </DialogsList>       
                </Flex>     
            </ScrollArea.Autosize>      
            <Box>
                <UpdateAlert></UpdateAlert>                  
                <Divider color={colors.borderColor}></Divider>
                <UserButton></UserButton>
            </Box>
        </Flex>
    );
}