import { Box, Text } from '@wix/design-system';
import React, { useEffect, ReactNode, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { TabsResponsiveState } from './TabsResponsiveState';
import { classes, st } from './TabsFilter.st.css.js';

export interface TabTitleProps<V> {
  tabIndex: number;
  state: TabsResponsiveState;
  text?: string;
  value: V | null | undefined;
  active?: boolean;
  counterBadge?: (value: V | null | undefined) => ReactNode;
}

function _TabTitle<V>({
  tabIndex,
  state,
  text,
  value,
  active,
  counterBadge,
}: TabTitleProps<V>) {
  const badge = counterBadge?.(value);
  const badgeRef = useRef<HTMLSpanElement>();

  useEffect(() => {
    if (badgeRef.current) {
      state.badges.set(tabIndex, badgeRef.current);
    }

    return () => {
      state.badges.delete(tabIndex);
    };
  }, [badgeRef.current]);

  return (
    <Box
      className={st(classes.root, { selected: !!active })}
      dataHook="tabs-filter-tab-title"
      verticalAlign="middle"
      align="center"
    >
      <Box maxWidth={state.itemMaxWidth} flexShrink={1} minWidth={0}>
        <Text className={st(classes.title)} dataHook="title-text" ellipsis>
          {text}
        </Text>
      </Box>
      {badge && (
        <Box dataHook="title-badge" marginLeft={`${state.itemBadgeMargin}px`}>
          <div
            ref={(node) => {
              if (node) {
                badgeRef.current = node;
              }
            }}
          >
            {badge}
          </div>
        </Box>
      )}
    </Box>
  );
}

export const TabTitle = observer(_TabTitle);
