import 'dayjs/locale/ru';

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

import dayjs from 'dayjs';
import { observer } from 'mobx-react';
import { HiOutlineChatBubbleLeftRight } from 'react-icons/hi2';
import {
  LuLogOut,
  LuMenu,
  LuSearch,
} from 'react-icons/lu';

import { showAlert } from '../../components/AlertRoot';
import { usePresentation } from '../../presentation/PresentationContext';
import { ROUTER } from '../../router/router';
import { channelStore } from '../../stores/channelStore';
import store from '../../stores/store';
import Header from '../../ui/Header';
import IconButton from '../../ui/IconButton';
import {
  Menu,
  MenuItem,
} from '../../ui/Menu';
import Page from '../../ui/Page';
import Popover from '../../ui/Popover';
import Tabs from '../../ui/Tabs';
import ChannelPage from '../ChannelPage/ChannelPage';
import DialogsList from './components/DialogsList';

dayjs.locale('ru');

const MainPage = () => {
  const {
    id,
    components: {
      MainSidebarHeaderCenter,
      MainDesktopSidebarShell,
      NoChannelSelected,
    },
  } = usePresentation();

  const desktopChannelSwitchBlocked =
    !store.isMobile() && !channelStore.initialChannelSwitchReady;

  const [menuOpen, setMenuOpen] = useState(false);
  const menuTargetRef = useRef<HTMLButtonElement>(null);
  const [search, setSearch] = useState('');
  const [searchActive, setSearchActive] = useState(false);

  const onLogout = () => {
    setMenuOpen(false);
    showAlert({
      title: 'Выйти из аккаунта?',
      content: 'Вы уверены, что хотите выйти?',
      buttons: [
        {
          text: 'Выйти',
          onClick: () => {
            localStorage.clear();
            window.location.reload();
          },
        },
        { text: 'Отмена' },
      ],
    });
  };

  const tabs: { id: 'member' | 'join'; label: string }[] = [
    { id: 'member', label: 'Активные' },
    { id: 'join', label: 'Новые' },
  ];

  const sidebar = (
    <>
      {!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={
          <IconButton ref={menuTargetRef} onClick={() => setMenuOpen(true)}>
            <LuMenu />
          </IconButton>
        }
        center={
          <MainSidebarHeaderCenter
            searchActive={searchActive}
            search={search}
            onSearchChange={setSearch}
            onSearchBlur={() => {
              if (!search) setSearchActive(false);
            }}
          />
        }
        right={
          <IconButton onClick={() => setSearchActive((v) => !v)}>
            <LuSearch />
          </IconButton>
        }
        subnavbar={store.mode == 'full' && (
          <Tabs
            value={store.channelTab}
            onChange={(v) => store.setChannelTab(v)}
            tabs={tabs}
          />)
        }
      />}

      <div className="flex-1 overflow-y-auto tg-scroll">
        <DialogsList
          selectChannelID={store.selectChannel?._id ?? null}
          channelTab={store.channelTab}
          selectChannel={store.selectChannel}
          desktopChannelSwitchBlocked={desktopChannelSwitchBlocked}
          onSelectChannel={(channel) => {
            if (
              desktopChannelSwitchBlocked &&
              channel._id !== store.selectChannel?._id
            ) {
              return;
            }
            store.setSelectChannel(channel);
            if (store.isMobile() && channel?._id) {
              ROUTER().ChannelPage.move({ channelID: channel._id });
            }
          }}
        />
      </div>

      <Popover
        opened={menuOpen}
        onClose={() => setMenuOpen(false)}
        target={menuTargetRef.current}
        width={240}
      >
        <Menu>
          {store.mode == 'full' && (
            <MenuItem
              icon={<LuLogOut />}
              title="Выйти"
              danger
              onClick={onLogout}
            />
          )}
          {store.mode != 'full' && (
            <MenuItem
              icon={<HiOutlineChatBubbleLeftRight />}
              title="О приложении"
              onClick={() => setMenuOpen(false)}
            />
          )}
        </Menu>
      </Popover>
    </>
  );

  if (!store.isMobile()) {
    return (
      <Page className="flex-row">
        <MainDesktopSidebarShell>{sidebar}</MainDesktopSidebarShell>
        <div className="flex-1 flex flex-col min-w-0 relative">
          {store.selectChannel?._id ? (
            <ChannelPage channelID={store.selectChannel?._id} noPage />
          ) : (
            <NoChannelSelected />
          )}
        </div>
      </Page>
    );
  }

  return <Page>{sidebar}</Page>;
};

export default observer(MainPage);
