import * as React from 'react';
import { findAll } from 'highlight-words-core';
import styled from 'styled-components';

import type { JSX } from 'react';

export const HighlightContext = React.createContext<string[]>([]);

export type CatalogClassicHighlightProps = React.PropsWithChildren;

export function CatalogClassicHighlight(props: CatalogClassicHighlightProps): JSX.Element | null {
  const { children } = props;
  const searchWords = React.useContext(HighlightContext);

  if (!searchWords.length) {
    return children ? <>{children}</> : null;
  }

  function highlight(str: string, childIdx: number = 0) {
    const chunks = findAll({
      searchWords,
      textToHighlight: str,
    });

    return (
      <span data-component-name="CatalogClassic/CatalogClassicHighlight" key={childIdx}>
        {chunks.map((chunk, idx) => {
          const { end, highlight, start } = chunk;
          const text = str.substr(start, end - start);
          if (highlight) {
            return <HighlightedText key={idx}>{text}</HighlightedText>;
          } else {
            return text;
          }
        })}
      </span>
    );
  }

  if (typeof children === 'string') {
    return highlight(children);
  } else if (Array.isArray(children)) {
    return (
      <>
        {children.map((child, idx) =>
          typeof children === 'string' ? highlight(child, idx) : child || null,
        )}
      </>
    );
  } else {
    return <>children</> || null;
  }
}

const HighlightedText = styled.span`
  background-color: var(--search-highlight-bg-color);
  color: var(--search-highlight-text-color);
`;
