import React, { useEffect, FC, useRef, ReactType, useState } from 'react';
import DefaultLink, { LinkProps } from '../../blocks/Link';
import css from './index.module.css';
import { MilaGridColumn, MilaGridVoid } from '../../index';
import classnames from 'classnames';
import { NavigationItem, NavigationItemProps } from '../Footer';
import SimpleBar from 'simplebar-react';
export interface NavigationProps {
  items?: {
    name: string;
    Link?: ReactType;
    LinkProps: LinkProps;
    items?: {
      name: string;
      Link?: ReactType;
      LinkProps: LinkProps;
    }[];
  }[];
  LoginProps?: LinkProps;
  SignUpProps?: LinkProps;
  Link?: ReactType;
  setMobileNavOpen?: (open: boolean) => {};
  isStickyHeader: boolean;
  Search: ReactType;
  SearchProps: any;
  navigationItems: {
    name: string;
    items: {}[];
  }[];
  contactNavigation: {
    name: string;
    items: {
      Link: ReactType;
      LinkProps: LinkProps;
    }[];
  };
}

const Navigation: FC<NavigationProps> = ({
  items,
  LoginProps,
  SignUpProps,
  Link = DefaultLink,
  setMobileNavOpen,
  isStickyHeader,
  Search,
  SearchProps,
  navigationItems,
  contactNavigation,
}) => {
  const navigationElement = useRef(null);
  const node = useRef();
  const burgerRef = useRef();
  const mobileOverlay = useRef();

  const [isNavOpen, setIsNavOpen] = useState(false);

  const keepWholeNavigation = ['ch', 'de', 'gb', 'uk'].includes(
    SearchProps?.region?.toLowerCase(),
  );
  useEffect(() => {
    setMobileNavOpen(isNavOpen);
  }, [isNavOpen]);

  const handleClickOutside = (e): void => {
    if (!isNavOpen || !mobileOverlay.current) {
      return;
    }
    // @ts-ignore null check above
    if (mobileOverlay?.current?.contains(e.target)) {
      setIsNavOpen(false);
    }
  };

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);

    return (): void => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  });

  return (
    <>
      <MilaGridColumn columns={['xl-6', 'xxl-5']}>
        <ul
          className={classnames(css.navigation__list, {
            [css.navigation__listSticky]: isStickyHeader,
          })}
        >
          {items &&
            items.map(item => {
              return (
                <li className={css.navigation__listItem} key={item.name}>
                  <Link
                    {...item.LinkProps}
                    className={css.navigation__listLink}
                    activeClassName={css.navigation__listLinkActivePage}
                  >
                    {item.name}
                  </Link>
                </li>
              );
            })}
        </ul>
      </MilaGridColumn>
      <MilaGridColumn
        columns={['sm-4']}
        data-testid="Navigation"
        divRef={node}
        className={css.nav__buttonWrapper}
      >
        <div className={css.navIcon__wrapper}>
          <div
            className={classnames(css.navIcon, {
              [`${css.navIcon__active}`]: isNavOpen,
              [`${css.navIcon__sticky}`]: isStickyHeader,
            })}
            ref={burgerRef}
            onClick={(): void => setIsNavOpen(!isNavOpen)}
          >
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
        {keepWholeNavigation && (
          <>
            <div
              className={css.navigation__wrap}
              data-testid="Navigation"
              ref={node}
            >
              <nav className={css.navigation} ref={navigationElement}>
                <div className={css.navigation__actions}>
                  <div className={css.navigation__search}>
                    <Search
                      {...SearchProps}
                      stickyHeader={isStickyHeader}
                      mobileNavOpen={isNavOpen}
                    />
                  </div>

                  <div className={css.navigation__login}>
                    {LoginProps && (
                      <Link
                        {...LoginProps}
                        variant={`navigation${isStickyHeader ? 'Blue' : ''}`}
                      />
                    )}
                  </div>
                  <div className={css.navigation__signUp}>
                    {SignUpProps && (
                      <Link
                        {...SignUpProps}
                        variant={`navigation${isStickyHeader ? 'Blue' : ''}`}
                      />
                    )}
                  </div>
                </div>
              </nav>
            </div>
          </>
        )}
      </MilaGridColumn>

      {isNavOpen && (
        <div className={css.navigation__mobileOverlay} ref={mobileOverlay} />
      )}
      <div
        className={classnames(css.navigation__mobileWrapper, {
          [css.navigation__mobileWrapperOpen]: isNavOpen,
        })}
      >
        <SimpleBar>
          <div className={classnames('mila-container', css.navigation__mobile)}>
            <MilaGridVoid>
              <MilaGridColumn columns={['sm-12']}>
                <nav className={css.navigation} ref={navigationElement}>
                  <div className={css.navigation__actions}>
                    <div className={css.navigation__search}>
                      <Search
                        {...SearchProps}
                        stickyHeader={isStickyHeader}
                        mobileNavOpen={isNavOpen}
                      />
                    </div>
                    <div className={css.navigation__login}>
                      {LoginProps && (
                        <Link {...LoginProps} variant="secondary" />
                      )}
                    </div>

                    <div className={css.navigation__signUp}>
                      {SignUpProps && (
                        <Link {...SignUpProps} variant="secondary" />
                      )}
                    </div>
                  </div>
                </nav>
              </MilaGridColumn>
              <MilaGridColumn columns={['sm-12']}>
                <ul className={css.navigation__list}>
                  {items &&
                    items.map(item => {
                      return (
                        <li
                          className={css.navigation__listItem}
                          key={item.name}
                        >
                          <Link
                            {...item.LinkProps}
                            className={css.navigation__listLink}
                            activeClassName={css.navigation__listLinkActivePage}
                          >
                            {item.name}
                          </Link>
                        </li>
                      );
                    })}
                </ul>
                {navigationItems &&
                  navigationItems.map((item, i) => (
                    <div className={css.navigation__column} key={i}>
                      <input
                        className={css.navigation__accordionInput}
                        type="checkbox"
                        id={item.name}
                        defaultChecked={false}
                      />
                      <label
                        htmlFor={item.name}
                        className={css.navigation__accordionLabel}
                      >
                        {item.name}
                      </label>
                      <div className={css.navigation__accordionContent}>
                        <ul className={css.navigation__navigationList}>
                          {item.items &&
                            item.items.map((item: NavigationItemProps, i) =>
                              !item.hideInPartnerPages ? (
                                <NavigationItem
                                  key={i}
                                  Link={item.Link}
                                  LinkProps={item.LinkProps}
                                />
                              ) : null,
                            )}
                        </ul>
                      </div>
                    </div>
                  ))}
                {contactNavigation && (
                  <div className={css.navigation__column}>
                    <input
                      className={css.navigation__accordionInput}
                      type="checkbox"
                      id="contact"
                      defaultChecked={false}
                    />
                    <label
                      htmlFor="contact"
                      className={css.navigation__accordionLabel}
                    >
                      {contactNavigation.name}
                    </label>
                    <div className={css.navigation__accordionContent}>
                      <ul className={css.navigation__navigationList}>
                        {contactNavigation.items &&
                          contactNavigation.items.map(
                            (item: NavigationItemProps, i) => (
                              <NavigationItem
                                key={i}
                                Link={item.Link}
                                LinkProps={item.LinkProps}
                                info={item.info}
                              />
                            ),
                          )}
                      </ul>
                    </div>
                  </div>
                )}
              </MilaGridColumn>
            </MilaGridVoid>
          </div>
        </SimpleBar>
      </div>
    </>
  );
};

export default Navigation;
