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

import React, {
  useEffect,
  useRef,
  useState,
} 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 { ShmChannelType } from '../../api/types';
import { goBack } from '../../router/router';
import store from '../../stores/store';
import MessagesBlock, {
  MessagesBlockRefProps,
} from './components/MessagesBlock';
import RichMessagebar, {
  RichMessagebarRefProps,
} from './components/RichMessagebar';

dayjs.locale("ru");



const ChannelPage = ({ noPage, channelID }: {
    noPage?: boolean;
    channelID?: string;
}) => {




    const richMessagebarRef = useRef<RichMessagebarRefProps | null>(null);

    const [selectChannel, setSelectChannel] = useState<ShmChannelType | null>(null);



    const refreshChannel = () => {

        setSelectChannel(null);
        setJoinInChannel(null);
        if (channelID) {


            rpc.channelInfo({
                channel: channelID,
            }).then(({ result: data }) => {
                if (data) {
                    setSelectChannel(data ?? null);

                    setJoinInChannel(data?.members?.find((member) => member.owner == store.userID) ? true : false);

                }
            });
        }
    }

    useEffect(() => {


        refreshChannel();




    }, [channelID]);

    /* useEffect(() => {
         if (selectChannel) {
 
             loadMessages();
 
             interval.current = setInterval(() => {
                 loadMessages();
             }, 5000);
 
             return () => {
                 if (interval.current) {
                     clearInterval(interval.current);
                 }
 
             };
 
         }
     }, [selectChannel]);*/



    const [joinInChannel, setJoinInChannel] = useState<boolean | null>(null);


    const messagesBlockRef = useRef<MessagesBlockRefProps | null>(null);



    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={
                <div className="text-sm ml-3">{selectChannel?.name}</div>
            }
            right={
                store.isMobile() && <>
                    <Link
                        onClick={() => {

                            goBack();


                        }}

                    >

                        <MdClose size={24} />

                    </Link>

                </>
            }
        ></Navbar>}



        {(!selectChannel?.closed && joinInChannel != null && !!selectChannel?._id) && <>{joinInChannel ? <RichMessagebar

            ref={richMessagebarRef}
            selectChannelID={selectChannel?._id}

            onSended={() => {
                messagesBlockRef.current?.loadMessages();
            }}

        /> : <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 (selectChannel?._id) {
                rpc.joinChannel({
                    channel: selectChannel?._id,
                }).then(() => {
                    refreshChannel();
                });
            }

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

        <MessagesBlock ref={messagesBlockRef} selectChannel={selectChannel} onReply={(msg) => {
            richMessagebarRef.current?.setReplyMsg(msg);
        }} onChannelChange={() => {
            refreshChannel();
        }} />

    </PageWrapper>

    );
};

export default observer(ChannelPage);
