import { useSelector } from 'react-redux';
import { useRouter } from 'next/router';

import { getUserAccountIdSelector, getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import { getMenuCollection, getUserMenuCollections } from '@/modules/layout/helpers';

type MenuType = {
  href: string;
  title: string;
  subMenu: MenuType[];
  componentProps?: {
    inHouseMenuSettings: object;
  };
};

type TitleHrefMap = {
  [key: string]: string;
};

function extractTitleHref(menuCollection: MenuType[]) {
  return menuCollection.reduce((acc, item) => {
    let subMenu = {};

    if (item.href && item.title) {
      acc[item.href] = item.title;
    }

    if (item.subMenu) {
      subMenu = extractTitleHref(item.subMenu);
    }

    if (item.subMenu?.[0]?.componentProps?.inHouseMenuSettings) {
      subMenu = {
        ...subMenu,
        ...extractTitleHref(Object.values(item.subMenu[0].componentProps.inHouseMenuSettings)),
      };
    }

    return { ...acc, ...subMenu };
  }, {} as TitleHrefMap);
}

function useTitle() {
  const userAccountId = useSelector(getUserAccountIdSelector);
  const userPermissions = useSelector(getUserPermissionsSelector);
  const router = useRouter();

  const pathname = router.asPath.split('?')[0];
  const pathnameSegments = pathname.split('/').reduce((acc: string[], val) => {
    const last = acc[acc.length - 1];

    if (val) {
      acc.push(`${last || ''}/${val}`);
    }

    return acc;
  }, []);

  const menuList = {
    ...extractTitleHref(getMenuCollection(userAccountId, userPermissions)),
    ...extractTitleHref(getUserMenuCollections(userPermissions)),
  };

  let title = '';
  // eslint-disable-next-line no-restricted-syntax
  for (const segment of pathnameSegments.reverse()) {
    title = menuList[segment];
    if (title) {
      break;
    }
  }

  return `${title ? `${title} - ` : ''}Video Manager`;
}

export default useTitle;
