// @flow
import React from 'react';
import styled from 'styled-components';
import { flatten } from 'lodash';
import { v4 as guid } from 'uuid';
import { getPaletteColor } from '../../../../mixins/branding';
import { Box } from '../../../../primitives/box';
import { Span } from '../../../typography/span';
import { getBoxShadow } from './default-search-result.css-rules';
import { HideAccessibly } from '../../../../primitives';

export type DefaultSearchResultProps = {
  isSelected: boolean,
  isFirst: boolean,
  matchedValue?: string,
  text: string,
};
export const DefaultSearchResult = ({
  isSelected,
  isFirst,
  matchedValue,
  text,
}: DefaultSearchResultProps) => {
  let regex;
  let contentParts = [text];
  let regexMatches = [];
  if (matchedValue != null && matchedValue !== '') {
    regex = new RegExp(matchedValue, 'ig');
    contentParts = text.split(regex);
    regexMatches = text.match(regex) ?? [];
  }

  return (
    <DefaultSearchResultOuter fontSize="f1" isSelected={isSelected}>
      <DefaultSearchResultInner isSelected={isSelected} isFirst={isFirst}>
        <HideAccessibly>{text}</HideAccessibly>
        <span aria-hidden>
          {flatten(
            contentParts.map((part) => (
              <span key={guid()}>
                {part}
                <Span bold>{regexMatches.shift()}</Span>
              </span>
            )),
          )}
        </span>
      </DefaultSearchResultInner>
    </DefaultSearchResultOuter>
  );
};

const getBorderTopColor = ({ isFirst, isSelected, theme }) => {
  if (isSelected) {
    return getPaletteColor('greyscale-black')({ theme });
  }

  return getPaletteColor(isFirst ? 'white' : 'greyscale-light')({ theme });
};

const DefaultSearchResultInner = styled(Box)`
  padding: 11px 0;
  border-top: solid 1px ${getBorderTopColor};
`;

const DefaultSearchResultOuter = styled(Span)`
  color: ${getPaletteColor('greyscale-black')};
  background: ${getPaletteColor('white')};
  display: block;
  padding: 0 20px;
  width: 100%;
  text-align: left;
  box-shadow: ${getBoxShadow};
  border-radius: inherit;
  line-height: 1.4;

  &:hover {
    background: ${getPaletteColor('background')};
  }

  &:focus {
    border: solid ${getPaletteColor('greyscale-black')} 2px;
  }
`;
