import React, { ReactNode, useEffect, useState } from 'react';
import Helmet from 'react-helmet';
import { AttentionBanner, Box } from '@nova-hf/ui';
import classNames from 'classnames/bind';
import ContactBubbleWrapper from 'components/contact-bubble-wrapper/ContactBubbleWrapper';
import { Devtools } from 'components/devtools/Devtools';
import Footer from 'containers/footer/Footer';
import Header from 'containers/header/Header';
import { MegaMenu } from 'containers/mega-menu/MegaMenu';
import SalesLocationPrompt from 'containers/sales-location/SalesLocationPrompt';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import { SnackbarProvider } from 'notistack';
import UI from 'store/ui';
import { helmet } from 'utils/helmet';

import AuthenticationStatus from '../../containers/authentication-status/AuthenticationStatus';
import Authentication from '../../store/authentication';
import notistackCustomStyles from '../../styles/notistackCustomStyles.module.scss';
import { useInternalNotesQuery } from '../../typings/graphql';

import s from './AppLayout.module.scss';

const cn = classNames.bind(s);

interface IAppLayoutProps {
  ui?: UI;
  authentication?: Authentication;
  children: ReactNode;
}

const isDev = process.env.NODE_ENV === 'development';

const AppLayout = ({ ui, children, authentication }: IAppLayoutProps) => {
  if (!ui) return null;
  const router = useRouter();
  const isStaff = authentication?.isStaff;
  const isHidden = ui.headerStyle === 'none';
  const [isReady, setIsReady] = useState(false);
  const hasNationalId = !!router?.query?.ssn?.length;

  const { data } = useInternalNotesQuery({
    variables: {
      input: {
        customer_national_id: router?.query.ssn,
      },
    },
    skip: !hasNationalId,
  });

  const hideHeaderForMessage = hasNationalId && !!data?.internalNotes.length;

  // To disable body scroll when megamenu is open.
  useEffect(() => {
    document.body.style.height = ui.isMegaMenuOpen || ui.hasMultiMenu ? '100vh' : '';
    document.body.style.overflowY = ui.isMegaMenuOpen || ui.hasMultiMenu ? 'hidden' : 'auto';
  }, [ui.isMegaMenuOpen, ui.hasMultiMenu]);

  useEffect(() => {
    authentication?.getSalesLocations();
    setIsReady(true);
  }, []);

  if (!isReady) {
    return null;
  }

  return (
    <>
      {isReady && <MegaMenu isOpen={ui.isMegaMenuOpen} />}
      <div className={s.layout} id="appLayout">
        <Helmet {...helmet} />
        <SalesLocationPrompt />
        <SnackbarProvider
          maxSnack={3}
          autoHideDuration={5000}
          anchorOrigin={{
            vertical: 'top',
            horizontal: 'center',
          }}
          className={notistackCustomStyles.toast}
          classes={{
            variantSuccess: notistackCustomStyles.toastSuccess,
            variantError: notistackCustomStyles.toastError,
          }}
        >
          <div
            className={cn({
              [s.contentWrapperWithSideMenu]: ui.hasSideMenu,
              [s.contentWrapperWithCustomerMenu]: ui.hasCustomerMenu,
            })}
          >
            {((!isHidden && !isStaff) || (!isHidden && isStaff && !hideHeaderForMessage)) && (
              <Header />
            )}
            {hasNationalId && data && isStaff && (
              <>
                {data?.internalNotes?.map((note, index) => (
                  <Box key={index} paddingX={10}>
                    <AttentionBanner
                      key={index}
                      icon="warning"
                      regularText={note?.note}
                      strongText={note?.title}
                    />
                    {index !== data?.internalNotes?.length - 1 && (
                      <Box borderBottomStyle="solid" borderColor="black100" borderWidth="1px"></Box>
                    )}
                  </Box>
                ))}
              </>
            )}
            <Box
              marginTop={{
                sm: ui.hasSideMenu ? 20 : ui.hasCustomerMenu ? 9 : 0,
                md: ui.hasCustomerMenu ? 14 : 0,
                lg: 0,
              }}
            >
              {children}
            </Box>
            {isDev && <Devtools />}
            {!ui.isHiddenFooter && isReady && <Footer />}
          </div>
          <AuthenticationStatus />
          <ContactBubbleWrapper />
        </SnackbarProvider>
      </div>
    </>
  );
};

export default inject('ui', 'authentication')(observer(AppLayout));
