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';
import MessageReactionPopover, {
  MessageReactionPopoverRefProps,
} from './MessageReactionPopover';

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 SMOOTH_SCROLL_MAX_DISTANCE_PX = 320;

const MessagesBlock = observer(() => {
    const pageRef = useRef<HTMLDivElement | null>(null);
    const messagePopoverRef = useRef<MessagePopoverRefProps | null>(null);
    const messageReactionPopoverRef = useRef<MessageReactionPopoverRefProps | 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(() => {
                const el = pageRef.current;
                if (!el) {
                    return;
                }
                const maxScrollTop = Math.max(0, el.scrollHeight - el.clientHeight);
                const distanceToBottom = maxScrollTop - el.scrollTop;
                el.scrollTo({
                    top: maxScrollTop,
                    behavior:
                        distanceToBottom > 0 && distanceToBottom <= SMOOTH_SCROLL_MAX_DISTANCE_PX
                            ? 'smooth'
                            : 'auto',
                });
            });
        }, 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]);

    const initialScrollToBottomCalled = useRef(false);

    useEffect(() => {
        if (channelStore.messagesList?.length && pageRef.current) {
            if (!initialScrollToBottomCalled.current) {
                initialScrollToBottomCalled.current = true;

                scrollToBottom();
            }
        }
    }, [channelStore.messagesList?.length]);

    useEffect(() => {
        if (!channelStore.pendingScrollToBottom) {
            return;
        }
        if (!channelStore.messagesList?.length) {
            return;
        }
        scrollToBottom();
        channelStore.clearPendingScrollToBottom();
    }, [channelStore.messagesList]);

    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">

            <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);
                            }}
                            onReactionClick={(msg) => {
                                messageReactionPopoverRef.current?.open({
                                    msg: msg,
                                    onChange: () => {
                                        channelStore.loadMessages();
                                    },
                                });
                            }}
                            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>
            <MessageReactionPopover
                ref={messageReactionPopoverRef}
            />

            <MessagePopover


                ref={messagePopoverRef}
            />


        </div>
    </>


});

export default MessagesBlock;
