import 'dayjs/locale/ru';

import { useEffect } from 'react';

import dayjs from 'dayjs';
import { observer } from 'mobx-react';

import { rpc, rpcClient } from '../../api/request';
import { ROUTER } from '../../router/router';
import store from '../../stores/store';
import Page from '../../ui/Page';
import Spinner from '../../ui/Spinner';

dayjs.locale('ru');

const LoadingPage = () => {
  const init = async () => {
    const searchParams = new URLSearchParams(window.location.search);

    const mode = await rpc.mode();
    if (mode.result == 'widget') {
      rpcClient.setToken(() => {
        return searchParams.get('token') ?? null;
      });

      const channel = searchParams.get('channel');

      store.loadUser().then(() => {
        if (channel) {
          store.setIsFixedChannel(true);
          ROUTER().ChannelPage.move({ channelID: channel });
        } else {
          ROUTER().MainPage.move({});
          store.setIsFixedChannel(false);
        }
      });
    } else {
      rpcClient.setUnauthorizedHandler(() => {
        localStorage.removeItem('token');
        window.location.reload();
      });

      rpcClient.setToken(() => localStorage.getItem('token') ?? null);

      store.setMode(mode.result ?? 'widget');

      if (localStorage.getItem('token')) {
        store.loadUser().then(() => ROUTER().MainPage.move({}));
      } else {
        ROUTER().LoginPage.move({});
      }
    }
  };

  useEffect(() => {
    init();
  }, []);

  return (
    <Page className="items-center justify-center">
      <div className="my-auto flex flex-col items-center gap-3">
        <Spinner size={32} />
      </div>
    </Page>
  );
};

export default observer(LoadingPage);
