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 {
    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' | 'closed'; label: string }[] = [
    { id: 'member', label: 'Активные' },
    { id: 'join', label: 'Новые' },
    { id: 'closed', label: 'Закрытые' },
  ];

  const baseTabs: { id: 'member' | 'join' | 'closed'; label: string }[] = [
    { id: 'member', label: 'Активные' },
    { id: 'closed', label: 'Закрытые' },
  ];

  const sidebar = (
    <>
      {!store.cap ? <Header
        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.authEnabled && (
          <Tabs
            value={store.channelTab}
            onChange={(v) => store.setChannelTab(v)}
            tabs={tabs}
          />)
        }
      /> :

        <Tabs
          value={store.channelTab}
          onChange={(v) => store.setChannelTab(v)}
          tabs={baseTabs}
        />}

      <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.authEnabled && (
            <MenuItem
              icon={<LuLogOut />}
              title="Выйти"
              danger
              onClick={onLogout}
            />
          )}
          {store.authEnabled && (
            <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);
