import { Tabbar } from '@taroify/core';
import classNames from 'classnames';
import { useCallback } from 'react';

import { APP_TAB_BAR_ID, RoleType, PageType, PageUrl } from '@/constants/app';
import { ANCHOR_TAB_LIST, COMPANY_TAB_LIST, TabItemType } from '@/hooks/use-config';
import useMessage from '@/hooks/use-message';
import useRoleType from '@/hooks/user-role-type';
import { logWithPrefix } from '@/utils/common';
import { switchTab } from '@/utils/route';

import './index.less';

interface IProps {
  className?: string;
  type: PageType;
}

const PREFIX = 'base-tab-bar';
const log = logWithPrefix('tab-bar');

const TabItem = (props: { item: TabItemType }) => {
  const { item } = props;
  const { unReadCount } = useMessage();
  return (
    <div className={`${PREFIX}__item_content`}>
      {item.text}
      {item.type === PageType.Message && unReadCount > 0 && (
        <>
          {unReadCount > 999 ? (
            <div className={`${PREFIX}__item_content__badge`} />
          ) : (
            <div className={`${PREFIX}__item_content__num-badge`}>{Math.min(unReadCount, 999)}</div>
          )}
        </>
      )}
    </div>
  );
};

function BaseTabBar({ className, type }: IProps) {
  const roleType = useRoleType();

  const tabs = roleType === RoleType.Anchor ? ANCHOR_TAB_LIST : COMPANY_TAB_LIST;

  const handleTabClick = useCallback(
    (value: PageType) => {
      if (value === type) {
        return;
      }
      const item = tabs.find((i: TabItemType) => i.type === value);
      log('tab bar changed', value, item?.pagePath);
      item && switchTab(item.pagePath as PageUrl);
    },
    [tabs, type]
  );

  // useEffect(() => {
  //   const item = tabs.find((i: TabItemType) => i.type === currentPage);
  //   log('effect', roleType, tabs, currentPage, item);
  //   if (!item) {
  //     dispatch(changeHomePage(tabs[0].type));
  //     switchTab(tabs[0].pagePath as PageUrl);
  //   }
  // }, [roleType, tabs, currentPage, dispatch]);

  return (
    <div className={classNames(`${PREFIX}__wrapper`, className)} id={APP_TAB_BAR_ID}>
      <Tabbar className={PREFIX} value={type}>
        {tabs.map((item: TabItemType) => {
          return (
            <Tabbar.TabItem
              key={item.pagePath}
              value={item.type}
              onClick={() => handleTabClick(item.type)}
              className={classNames(`${PREFIX}__item`, { selected: item.type === type })}
            >
              <TabItem item={item} />
            </Tabbar.TabItem>
          );
        })}
      </Tabbar>
    </div>
  );
}
export default BaseTabBar;
