import 'dayjs/locale/ru'; // load on demand

import React, { useEffect } from 'react';

import dayjs from 'dayjs';
import {
  Button,
  Link,
  Navbar,
  Page,
} from 'konsta/react';
import { observer } from 'mobx-react';
import { MdClose } from 'react-icons/md';

import { rpc } from '../../api/request';
import { goBack } from '../../router/router';
import { channelStore } from '../../stores/channelStore';
import store from '../../stores/store';
import MessagesBlock from './components/MessagesBlock';
import RichMessagebar from './components/RichMessagebar';

dayjs.locale("ru");

const ChannelPageContent = observer(({ noPage }: { noPage?: boolean }) => {



    const PageWrapper = ({ children }: {
        children: React.ReactNode;
    }) => {

        if (noPage) {

            return <div
                className='relative w-full h-full'>{children}</div>;
        }

        return (
            <Page className="ios:bg-white ios:dark:bg-black overflow-hidden">
                {children}
            </Page>
        );


    }

    return (<PageWrapper>



        {!store.cap && <Navbar
            title={
                !!channelStore.channel?.name ? channelStore.channel?.name : 'Диалог'
            }
            right={
                store.isMobile() && <>
                    <Link
                        onClick={() => {

                            goBack();


                        }}

                    >

                        <MdClose size={24} />

                    </Link>

                </>
            }
        ></Navbar>}



        {(!channelStore.channel?.closed && channelStore.joinInChannel != null && !!channelStore.channel?._id) && <>{channelStore.joinInChannel ? <RichMessagebar
        /> : store.mode == "full" ? <div


            style={{
                height: 'auto',
            }}
            className={`left-0 z-10 bottom-0 absolute  w-full  p-2 bg-ios-light-surface-2 dark:bg-ios-dark-surface-2 `}
        > <Button onClick={() => {

            if (channelStore.channel?._id) {
                rpc.joinChannel({
                    channel: channelStore.channel._id,
                }).then(({ result }) => {
                    if (result) {
                        channelStore.updateChannelInfo();
                    }
                });
            }

        }}>
                Присоединиться
            </Button>
        </div> : null}
        </>}

        <MessagesBlock />

    </PageWrapper>

    );
});

const ChannelPage = ({ noPage, channelID }: {
    noPage?: boolean;
    channelID?: string;
}) => {
    useEffect(() => {
        channelStore.openChannel(channelID);
        return () => channelStore.stopMessagesPolling();
    }, [channelID]);

    return <ChannelPageContent noPage={noPage} />;
};

export default observer(ChannelPage);
