import { styled } from '@mui/material/styles';
import type { ClassNameMap } from '@mui/styles/withStyles';
import clsx from 'clsx';
import { Fragment, memo, useMemo } from 'react';
import Highlighter, { HighlighterProps } from 'react-highlight-words';
import type { ColoredTextWithBGProps } from '../colored-text-with-bg';
import { ColoredTextWithBG } from '../colored-text-with-bg';
import type { CompanyIconProps } from '../company-icon';
import { CompanyIcon } from '../company-icon';
import { TextWithTooltip } from '../text-with-tooltip';

const StyledRoot = styled('div')({
  display: 'flex',
  flexDirection: 'row',
  width: '100%'
});

const StyledIconsContainer = styled('div', { shouldForwardProp: prop => prop !== 'variant' })<{
  variant: TenantProps['variant'];
}>(({ theme, variant }) => ({
  display: 'flex',
  alignItems: 'center',
  paddingRight: variant === 'global-search' ? theme.spacing(1) : theme.spacing(2)
}));

const StyledTextsContainer = styled('div')({
  display: 'flex',
  flexDirection: 'column',
  flexWrap: 'wrap',
  width: '100%',
  minWidth: 0
});

const StyledTitleContainer = styled('div', { shouldForwardProp: prop => prop !== 'variant' })<{
  variant?: TenantProps['variant'];
}>(({ theme, variant }) => ({
  display: 'flex',
  alignItems: 'center',
  flexDirection: 'row',
  '& .companyTitle': {
    ...(variant === 'global-search' ? theme.typography.h6 : theme.typography.h5),
    color: theme.palette.primary[500],
    paddingRight: theme.spacing(0.5)
  }
}));

const StyledSubtitleContainer = styled('div', { shouldForwardProp: prop => prop !== 'variant' })<{
  variant?: TenantProps['variant'];
}>(({ theme, variant }) => ({
  marginTop: variant === 'global-search' ? 0 : theme.spacing(0.5),
  width: '100%',
  '& .subTextsContainer': {
    display: 'flex',
    alignItems: 'center'
  },
  '& .subText': {
    ...(variant === 'global-search' ? theme.typography.caption1 : theme.typography.caption2),
    display: 'block',
    color: variant === 'global-search' ? theme.palette.primary[400] : theme.palette.primary[500],
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    '&.firstSubText': {
      color: theme.palette.primary[400],
      overflow: 'visible'
    }
  },
  '& .subDot': {
    display: 'block',
    minWidth: theme.spacing(0.5),
    maxWidth: theme.spacing(0.5),
    height: theme.spacing(0.5),
    margin: theme.spacing(0, 1),
    borderRadius: '50%',
    backgroundColor: theme.palette.primary[400]
  }
}));

export interface TenantProps {
  /**
   * Title of the component.
   */
  title: string;
  /**
   * Subtitle of the component.
   */
  subtitle?: string;
  /**
   * List of subtexts, will override subtitle.
   */
  subTexts?: string[];
  /**
   * Props which will be passed to the colored text with bg component.
   */
  companyStatusProps?: ColoredTextWithBGProps;
  /**
   * Props which will be passed to the company icon component.
   */
  companyIconProps: CompanyIconProps;
  /**
   * Custom class name in case you need to add custom styles to the component.
   */
  className?: string;
  /**
   * Override classes.
   */
  classes?: Partial<ClassNameMap<'root' | 'title'>>;
  /**
   * search words
   */
  hightLightSearchWords?: HighlighterProps['searchWords'];
  variant?: 'data-grid' | 'global-search';
}

const Tenant = (props: TenantProps) => {
  const {
    title: _title,
    subtitle,
    companyStatusProps,
    companyIconProps,
    subTexts,
    className,
    classes,
    hightLightSearchWords,
    variant = 'data-grid'
  } = props;

  const title = useMemo(
    () =>
      hightLightSearchWords ? (
        <Highlighter
          data-testid="subtitle"
          highlightClassName="highlight"
          searchWords={hightLightSearchWords}
          autoEscape
          textToHighlight={_title}
        />
      ) : (
        _title
      ),
    [_title, hightLightSearchWords]
  );

  const Subtitle = useMemo(
    () =>
      hightLightSearchWords ? (
        <Highlighter
          className="subText"
          data-testid="subtitle"
          highlightClassName="highlight"
          searchWords={hightLightSearchWords}
          autoEscape
          textToHighlight={subtitle || ''}
        />
      ) : (
        <span className="subText" data-testid="subtitle">
          {subtitle}
        </span>
      ),
    [hightLightSearchWords, subtitle]
  );

  return (
    <StyledRoot className={clsx(className, classes?.root)}>
      {companyIconProps.domain && (
        <StyledIconsContainer variant={variant}>
          <CompanyIcon {...companyIconProps} />
        </StyledIconsContainer>
      )}
      <StyledTextsContainer>
        <StyledTitleContainer variant={variant}>
          <TextWithTooltip
            disableInteractive={false}
            numOfLines={1}
            text={title}
            className={clsx('companyTitle', classes?.title)}
          />
          {companyStatusProps?.content && <ColoredTextWithBG {...companyStatusProps} />}
        </StyledTitleContainer>
        <StyledSubtitleContainer variant={variant}>
          {subTexts?.length ? (
            <div className="subTextsContainer" data-testid="subTexts">
              {subTexts.map((text, i) => (
                <Fragment key={`subText_${text}`}>
                  {i !== 0 && <span className="subDot" />}
                  <span className={clsx('subText', i === 0 && 'firstSubText')}>{text}</span>
                </Fragment>
              ))}
            </div>
          ) : (
            Subtitle
          )}
        </StyledSubtitleContainer>
      </StyledTextsContainer>
    </StyledRoot>
  );
};

Tenant.defaultProps = {
  companyStatusProps: {},
  subtitle: '',
  subTexts: []
};

const m = memo(Tenant);
export { m as Tenant };
