import 'dayjs/locale/ru';

import { useEffect, useLayoutEffect } from 'react';

import dayjs from 'dayjs';
import { observer } from 'mobx-react';
import { LuArrowLeft } from 'react-icons/lu';

import { rpc } from '../../api/request';
import { usePresentation } from '../../presentation/PresentationContext';
import { goBack } from '../../router/router';
import { channelStore } from '../../stores/channelStore';
import store from '../../stores/store';
import Button from '../../ui/Button';
import Header from '../../ui/Header';
import IconButton from '../../ui/IconButton';
import Page from '../../ui/Page';
import MessagesBlock from './components/MessagesBlock';
import RichMessagebar from './components/RichMessagebar';

dayjs.locale('ru');

const ChannelPageContent = observer(({ noPage }: { noPage?: boolean }) => {
  const {
    id,
    components: { ChannelHeaderCenter, JoinChannelBar },
  } = usePresentation();

  useEffect(() => {
    store.loadFastAnswers();
  }, []);

  const otherMember = channelStore.channel?.members?.find(
    (m) => m.owner != store.userID
  );
  const channelTitle = channelStore.channel?.name || 'Чат';
  const channelClosed = !!channelStore.channel?.closed;
  // Telegram-like under-title status. У нас нет реального онлайна и события
  // «typing», поэтому показываем нейтральный «был(а) недавно» для активных
  // чатов и явный «диалог закрыт» / «ожидает присоединения» для остальных.
  const channelStatus = channelClosed
    ? 'диалог закрыт'
    : channelStore.joinInChannel === false
    ? 'ожидает присоединения'
    : 'был(а) недавно';

  const header = !store.cap && (
    <Header
      className={
        id === 'whatsapp'
          ? '!bg-[var(--tg-bg-secondary)] border-[var(--tg-divider)]'
          : id === 'instagram'
            ? '!bg-[var(--tg-bg)] shadow-[0_1px_0_rgba(0,0,0,0.08)] dark:shadow-[0_1px_0_rgba(255,255,255,0.06)]'
            : ''
      }
      left={
        store.isMobile() ? (
          <IconButton onClick={() => goBack()}>
            <LuArrowLeft />
          </IconButton>
        ) : null
      }
      center={
        <ChannelHeaderCenter
          title={channelTitle}
          status={channelStatus}
          statusTone={
            channelClosed || channelStatus === 'был(а) недавно'
              ? 'muted'
              : 'accent'
          }
          avatarId={otherMember?.owner ?? channelStore.channel?._id ?? ''}
          avatarSize={40}
        />
      }
    />
  );

  const joinBar =
    !channelClosed &&
    channelStore.joinInChannel != null &&
    !!channelStore.channel?._id && (
      <>
        {channelStore.joinInChannel ? (
          <RichMessagebar />
        ) : store.mode == 'full' ? (
          <JoinChannelBar>
            <Button
              fullWidth
              onClick={() => {
                if (!channelStore.channel?._id) return;
                rpc
                  .joinChannel({ channel: channelStore.channel._id })
                  .then(({ result }) => {
                    if (result) channelStore.updateChannelInfo();
                  });
              }}
            >
              Присоединиться
            </Button>
          </JoinChannelBar>
        ) : null}
      </>
    );

  const content = (
    <>
      {header}
      <div className="flex-1 flex flex-col min-h-0 relative">
        <MessagesBlock />
      </div>
      {joinBar}
    </>
  );

  if (noPage) {
    return <div className="relative w-full h-full flex flex-col">{content}</div>;
  }

  return <Page>{content}</Page>;
});

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

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

export default observer(ChannelPage);
