import { Fragment } from 'react';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Title from '@material-hu/components/design-system/Title';

import { MAX_CATEGORIES_CHILDREN } from 'src/pages/dashboard/Learning/Settings/Categories/constants';
import { type CategoryAutocompleteOption } from 'src/pages/dashboard/Learning/Settings/Categories/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

const CATEGORY_SEPARATOR = ' > ';
const MINIMUM_SEGMENT_WIDTH = '24px';

type TruncatedCategoryPathProps = {
  option: CategoryAutocompleteOption;
  showMaxDepthErrorMessage?: boolean;
  showErrors?: boolean;
};

/**
 * Renders a category path with truncation.
 * When the path overflows, each segment is truncated proportionally,
 * showing the beginning of each category name with ellipsis.
 *
 * Example: "Category 1 > Subcategory > Child" becomes "Categ... > Subca... > Child..."
 */
export const TruncatedCategoryPath = ({
  option,
  showMaxDepthErrorMessage,
  showErrors,
}: TruncatedCategoryPathProps) => {
  const { t } = useLokaliseTranslation('validations');

  const segments = option.label.split(CATEGORY_SEPARATOR);
  const isSingleSegment = segments.length === 1;

  const getMaxDepthErrorMessage = () => {
    if (!option.childrenCount || !showErrors) return undefined;

    const hasReachedMaxChildrenCount =
      option.childrenCount >= MAX_CATEGORIES_CHILDREN;

    const shouldShowError =
      showMaxDepthErrorMessage && hasReachedMaxChildrenCount;

    const errorMessage = t('max_category_depth', {
      max: MAX_CATEGORIES_CHILDREN,
    });

    return shouldShowError ? errorMessage : undefined;
  };

  const maxDepthErrorMessage = getMaxDepthErrorMessage();

  if (isSingleSegment || maxDepthErrorMessage) {
    return (
      <Title
        title={option.label}
        description={maxDepthErrorMessage}
        variant="S"
        fontWeight="fontWeightSemiBold"
      />
    );
  }

  return (
    <Stack
      sx={{ flexDirection: 'row', alignItems: 'center', overflow: 'hidden' }}
    >
      {segments.map((segment, index) => (
        <Fragment key={segment}>
          {index > 0 && (
            <Typography
              component="span"
              variant="globalS"
              fontWeight="fontWeightSemiBold"
              sx={{ flexShrink: 0, px: 0.5 }}
            >
              {'>'}
            </Typography>
          )}
          <Typography
            component="span"
            variant="globalS"
            fontWeight="fontWeightSemiBold"
            sx={{
              flexShrink: 1,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              minWidth: MINIMUM_SEGMENT_WIDTH,
            }}
          >
            {segment}
          </Typography>
        </Fragment>
      ))}
    </Stack>
  );
};
