import {
    useEffect,
    useRef,
} from 'react';

import {
    Chip,
    Message,
    Toolbar,
} from 'konsta/react';
import { observer } from 'mobx-react';

import { rpc } from '../../../api/request';
import { showAlert } from '../../../components/AlertRoot';
import pattern from '../../../pattern.jpg';
import { channelStore } from '../../../stores/channelStore';
import store from '../../../stores/store';
import MessageItem from './MessageItem';
import MessagePinnedItem from './MessagePinnedItem';
import MessagePopover, { MessagePopoverRefProps } from './MessagePopover';

const MessagesSkeleton = () => {

    return <>

        {[1, 2, 3, 4].map((index) => {
            return <Message




                className='animate-pulse'

                key={index}
                type={index % 2 == 0 ? "received" : "sent"}


                text={"▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒"}


            />

        })}


    </>

}

const SCROLL_DEBOUNCE_MS = 300;

const MessagesBlock = observer(() => {
    const pageRef = useRef<HTMLDivElement | null>(null);
    const messagePopoverRef = useRef<MessagePopoverRefProps | null>(null);
    const scrollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

    const scrollToBottom = () => {
        if (scrollTimeoutRef.current) {
            clearTimeout(scrollTimeoutRef.current);
        }
        scrollTimeoutRef.current = setTimeout(() => {
            scrollTimeoutRef.current = null;
            requestAnimationFrame(() => {
                if (pageRef.current) {
                    pageRef.current.scrollTo({
                        top: pageRef.current.scrollHeight,
                        behavior: 'smooth',
                    });
                }
            });
        }, SCROLL_DEBOUNCE_MS);
    };

    useEffect(() => {
        if (channelStore.channel?._id) {
            channelStore.loadMessages();
            if (!channelStore.channel?.closed) {
                channelStore.startMessagesPolling(scrollToBottom);
            } else {
                channelStore.stopMessagesPolling();
            }
        }
        return () => {
            channelStore.stopMessagesPolling();
            if (scrollTimeoutRef.current) {
                clearTimeout(scrollTimeoutRef.current);
            }
        };
    }, [channelStore.channel?._id, channelStore.channel?.closed]);

    useEffect(() => {
        if (channelStore.messagesList?.length && pageRef.current) {
            scrollToBottom();
        }
    }, [channelStore.messagesList?.length]);

    const scrollByMessage = (_id: string | undefined) => {

        if (!_id) {
            console.warn("Не указан ID сообщения для скрола");
            return;
        }


        //Находим по #msg-<id> элемент и скроллим к нему в pageRef
        const element = document.getElementById(`msg-${_id}`);

        let offsetTop = element?.parentElement?.parentElement?.parentElement?.parentElement?.offsetTop;
        if (offsetTop && pageRef.current) {
            setTimeout(() => {
                if (offsetTop && pageRef.current) {
                    pageRef.current.scrollTo({
                        top: offsetTop - 100, // немного выше, чтобы не было внизу экрана
                        behavior: 'smooth',

                    });
                }
            }, 100);
        } else {
            console.warn(`Не найден элемент с ID msg-${_id}`);
        }


    }

    return <>

        {!!channelStore.pinnedMessage && <Toolbar top>

            <MessagePinnedItem
                onPin={() => {

                    rpc.pinnedMessage({
                        message: channelStore.pinnedMessage!._id,
                    }).then(() => {

                        channelStore.loadMessages();
                    });

                }}
                onClick={() => {
                    scrollByMessage(channelStore.pinnedMessage!._id);

                }}
                msg={channelStore.pinnedMessage}
            />


        </Toolbar>}
        <div ref={pageRef} className="overflow-y-scroll h-screen scroll-smooth">

            <div
                className='absolute top-0 left-0 w-full h-full bg-cover bg-center opacity-10'
                style={{
                    background: `url(${pattern})`
                }}
            >


            </div>
            <div className="flex flex-col relative z-1 px-4 mb-48">

                {channelStore.messagesLoading && !channelStore.messagesList?.length && (
                    <MessagesSkeleton />
                )}

                {channelStore.messagesList?.map((msg) => {
                    return (

                        <MessageItem
                            onReplayClick={(msg) => {
                                scrollByMessage(msg._id);
                            }}
                            onClick={() => {

                                messagePopoverRef.current?.open({
                                    msg: msg,

                                    onChange: () => {
                                        channelStore.loadMessages();
                                    },
                                    onPinned: () => {
                                        rpc.pinnedMessage({
                                            message: msg._id,
                                        }).then(() => {
                                            channelStore.loadMessages();
                                        });
                                    },
                                    onDelete: () => {
                                        rpc.channelDeleteMessage({
                                            message: msg._id,
                                            channel: channelStore.channel?._id,
                                        }).then(() => {
                                            channelStore.loadMessages();
                                        });
                                    },
                                    onReply: (msg) => {
                                        channelStore.setReplyMsg(msg);
                                    }

                                });


                            }}
                            onChange={() => {
                                channelStore.loadMessages();
                            }}
                            key={msg._id} msg={msg} />
                    );
                })}


                {!channelStore.channel?.closed && channelStore.channel?.type == "support" && channelStore.channel?.members?.find((member) => member.owner == store.userID) && <div

                    onClick={() => {

                        showAlert({
                            title: 'Вы уверены?',
                            content: 'Вы уверены, что хотите закрыть обращение?',
                            buttons: [

                                {
                                    text: 'Закрыть обращение',
                                    onClick: () => {
                                        rpc.channelClose({
                                            channel: channelStore.channel?._id,
                                        }).then(() => {
                                            channelStore.loadMessages();
                                            channelStore.refreshChannel();
                                        });
                                    },
                                },
                                {
                                    text: 'Отмена',
                                    onClick: () => {
                                        return;
                                    },
                                },
                            ],
                        });


                    }}
                    className='flex justify-center items-center cursor-pointer active:opacity-50 mt-2'>
                    <Chip>Закрыть обращение</Chip>
                </div>}

            </div>

            <MessagePopover


                ref={messagePopoverRef}
            />


        </div>
    </>


});

export default MessagesBlock;
