/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */
import {
  useState,
  useEffect,
  useRef,
  JSX
} from 'react';
import {useNavigate, useLocation} from 'react-router-dom';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faSignOutAlt} from '@fortawesome/free-solid-svg-icons';

import UserStoreService from 'services/user-store';
import {RootState, useAppDispatch, useAppSelector} from 'store';
import {selectIsAuthenticated, signoutThunk} from 'store/slices/Authentication.slice';
import text from './text';

import {SideMenu} from 'components/side-menu';
import urlRoutes from 'routers/url-routes';

import {
  TopNavigation,
  User,
  ApplicationId,
  UserInitials,
  MenuIcon,
  NavigationLeftSide
} from './style';

import logo from 'assets/images/phenix-logo-101x41.png';
import menuIcon from 'assets/images/icon/menu.svg';

const Header = (): JSX.Element => {
  const ref = useRef<HTMLDivElement | null>(null);
  const dispatch = useAppDispatch();
  const {search, pathname}: {search: string; pathname: string} = useLocation();
  const applicationId = useAppSelector((state: RootState) => state.authentication.applicationId);
  const [viewUserDetails, setViewUserDetails] = useState(false);
  const [showMenu, setShowMenu] = useState(false);
  const isLoggedIn = useAppSelector(selectIsAuthenticated);
  const navigate = useNavigate();
  const {phenixText} = text;
  let userInitials = '';

  if (applicationId) {
    userInitials = applicationId.substring(0, 2);
  }

  const handleClickOutside = (event: MouseEvent) => {
    if (ref.current && !ref.current.contains(event.target as Node)) {
      setViewUserDetails(false);
    }
  };

  const checkAndRedirect = async(): Promise<void> => {
    const applicationId = await UserStoreService.get('applicationId') as string;

    if (!applicationId) {
      return navigate(`/login/${search}`);
    }

    const lastVisitedRoutes = await UserStoreService.get<Record<string, string>>('lastVisitedRouteByApplicationId') as Record<string, string>;
    const lastVisitedRoute = lastVisitedRoutes[applicationId];
    const channelsPath = `/${urlRoutes.channels.path}/`;

    if (!pathname.includes(applicationId)) {
      if (lastVisitedRoute) {
        return navigate(`${lastVisitedRoute}${search}`);
      }

      return navigate(`${applicationId}${channelsPath}${search}`);
    }
  };

  // const setLastVisitedRoute = async(): Promise<void> => {
  //   const applicationId = await userStore.get('applicationId');
  //   const lastVisitedRoutes = await userStore.get('lastVisitedRouteByApplicationId') || {};

  //   await userStore.set('lastVisitedRouteByApplicationId', {
  //     ...lastVisitedRoutes,
  //     [applicationId]: pathname
  //   });
  // };

  useEffect(() => {
    checkAndRedirect();
  }, [isLoggedIn]);

  // useEffect(() => {
  //   setLastVisitedRoute();
  // }, [pathname]);

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

    return () => {
      document.removeEventListener('click', handleClickOutside, true);
    };
  });

  const handleLogout = async(): Promise<void> => {
    dispatch(signoutThunk());
  };

  const handleCaretClick = () => setViewUserDetails(!viewUserDetails);

  console.log('isLoggedIn', isLoggedIn);

  return (
    <TopNavigation isLoggedIn={isLoggedIn}>
      <NavigationLeftSide>
        {(isLoggedIn && applicationId) &&
          <MenuIcon
            onClick={() => setShowMenu(!showMenu)}
            src={menuIcon}
            alt="menuIcon"
          />
        }
        <img src={logo} alt={phenixText} />
      </NavigationLeftSide>
      {(isLoggedIn && applicationId) &&
        <>
          <User ref={ref} onClick={handleCaretClick} className="user-info">
            <UserInitials>{userInitials}</UserInitials>
            <ApplicationId className="testId-applicationId">{applicationId}</ApplicationId>
            <div className="testId-logoutButton" onClick={handleLogout} onKeyDown={undefined} role="button" tabIndex={-10}>
              <FontAwesomeIcon icon={faSignOutAlt} size="lg" />
            </div>
          </User>
          {showMenu &&
            <SideMenu showMenu={() => setShowMenu(!showMenu)} />
          }
        </>
      }
    </TopNavigation>
  );
};

export default Header;