// Hooks
import { FC, useCallback, useEffect, useMemo, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { useLocation } from 'react-router-dom';
import { useStore } from 'stores/StoreProvider';

// Components
import { OrganizationCard } from './OrganizationCard/OrganizationCard';
import { Bulletins } from './Bulletins';
import { NcirccMessages } from './NcirccMessages';
import Layout, { LeftSidebar, makeLeftSidebarContent } from 'components/Layout';

// Types
import { Page } from '../AppRoutes/constants';
import { RootStore } from '../../stores/RootStore';
import { TCommonMessages, useCommonMessages } from 'components/i18n';

// Styles
import dashboardStyles from 'components/Dashboard/Dashboard.module.scss';
import ncirccStyles from './Ncircc.module.scss';

export const NCIRCC_DASHBOARD: FC = observer(() => {
  // Общая локализация
  const commonTranslation: TCommonMessages = useCommonMessages();

  // Stores
  const rootStore: RootStore = useStore();
  const ncirccUiStore = rootStore.ncirccUiStore;

  const [visibleBulletin, setVisibleBulletin] = useState<boolean>(false);

  const leftSideBarContent = makeLeftSidebarContent(
    Page.NCIRCC_ORGANIZATION_CARD,
    commonTranslation.leftSidebar,
  );

  const onCloseBulletin = useCallback((): void => {
    setVisibleBulletin(false);
  }, []);

  const onShowBulletin = useCallback(
    (id: number): void => {
      setVisibleBulletin(true);
      ncirccUiStore.setSelectedBulletin(id);
    },
    [ncirccUiStore],
  );

  const { pathname } = useLocation();

  const [currentPage, setCurrentPage] = useState<
    | 'organization_card'
    | 'information_exchange_message'
    | 'information_exchange_bulletin'
    | null
  >(null);

  const pageMap = useMemo(() => {
    return {
      organization_card: <OrganizationCard />,
      information_exchange_message: <NcirccMessages />,
      information_exchange_bulletin: (
        <Bulletins
          visibleBulletin={visibleBulletin}
          onCloseBulletin={onCloseBulletin}
          onShowBulletin={onShowBulletin}
        />
      ),
    };
  }, [onCloseBulletin, onShowBulletin, visibleBulletin]);

  useEffect(() => {
    if (pathname === '/ncircc/organization_card') {
      setCurrentPage('organization_card');
    } else if (pathname === '/ncircc/information_exchange_message') {
      setCurrentPage('information_exchange_message');
    } else {
      setCurrentPage('information_exchange_bulletin');
    }
  }, [pathname, visibleBulletin, onShowBulletin, onCloseBulletin]);

  return (
    <Layout>
      <div className={dashboardStyles['wrapper']}>
        <div className={ncirccStyles['NCIRCCContainer']}>
          <LeftSidebar leftSideBarContent={leftSideBarContent} />
          <div className={ncirccStyles['content']}>
            {currentPage && pageMap[currentPage]}
          </div>
        </div>
      </div>
    </Layout>
  );
});
