import { Tabbar } from '@taroify/core';
import classNames from 'classnames';
import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';

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 { changeHomePage } from '@/store/actions';
import { selectHomePageType } from '@/store/selector';
import { logWithPrefix } from '@/utils/common';
import { switchTab } from '@/utils/route';

import './index.less';

interface IProps {
  className?: string;
}

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(props: IProps) {
  const { className } = props;
  const roleType = useRoleType();
  const currentPage = useSelector(selectHomePageType);
  const dispatch = useDispatch();

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

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

  // 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} defaultValue={currentPage}>
        {tabs.map((item: TabItemType) => {
          return (
            <Tabbar.TabItem
              key={item.pagePath}
              value={item.type}
              onClick={() => handleTabClick(item.type)}
              className={classNames(`${PREFIX}__item`, { selected: item.type === currentPage })}
            >
              <TabItem item={item} />
            </Tabbar.TabItem>
          );
        })}
      </Tabbar>
    </div>
  );
}
export default BaseTabBar;
