import * as React from 'react';
import styled from 'styled-components';

import type { JSX } from 'react';

import { breakpoints } from '@redocly/theme/core/utils';
import { useThemeHooks, useRecentSearches } from '@redocly/theme/core/hooks';
import { CloseIcon } from '@redocly/theme/icons/CloseIcon/CloseIcon';
import { RecentlyViewedIcon } from '@redocly/theme/icons/RecentlyViewedIcon/RecentlyViewedIcon';
import { Button } from '@redocly/theme/components/Button/Button';

export type SearchRecentProps = {
  onSelect: (value: string, index: number) => void;
  className?: string;
};

export function SearchRecent({ onSelect, className }: SearchRecentProps): JSX.Element | null {
  const { items, removeSearchHistoryItem } = useRecentSearches();
  const { useTranslate, useTelemetry } = useThemeHooks();
  const { translate } = useTranslate();
  const telemetry = useTelemetry();

  if (!items || !items.length) return null;

  const handleOnRemove = (e: React.MouseEvent<SVGSVGElement, MouseEvent>, item: string) => {
    e.stopPropagation();
    removeSearchHistoryItem(item);
    telemetry.sendSearchRecentRemoveButtonClickedMessage();
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>, item: string, index: number) => {
    if (e.key === 'Enter') {
      onSelect(item, index);
    }
  };

  return (
    <SearchRecentWrapper data-component-name="Search/SearchRecent" className={className}>
      <SearchRecentTitle data-translation-key="search.recent">
        {translate('search.recent', 'Recent searches')}
      </SearchRecentTitle>
      <SearchRecentItems>
        {items.map((item, index) => (
          <SearchRecentItem
            key={item}
            onClick={() => onSelect(item, index)}
            onKeyDown={(e) => handleKeyDown(e, item, index)}
            tabIndex={0}
            role="link"
          >
            <SearchRecentItemWrapper>
              <RecentlyViewedIcon color="--search-recent-item-text-color" />
              {item}
            </SearchRecentItemWrapper>
            <SearchRecentRemoveButton
              variant="ghost"
              icon={<CloseIcon />}
              onClick={(e: React.MouseEvent<SVGSVGElement, MouseEvent>) => handleOnRemove(e, item)}
              size="small"
            />
          </SearchRecentItem>
        ))}
      </SearchRecentItems>
    </SearchRecentWrapper>
  );
}

const SearchRecentWrapper = styled.div`
  display: flex;
  flex-direction: column;
`;

const SearchRecentTitle = styled.div`
  font-size: var(--search-recent-item-title-font-size);
  font-weight: var(--search-recent-item-title-font-weight);
  line-height: var(--search-recent-item-title-line-height);
  color: var(--search-recent-item-title-text-color);
  padding: var(--spacing-lg) var(--spacing-lg) var(--spacing-xxs) var(--spacing-lg);
`;

const SearchRecentItems = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-start;
`;

const SearchRecentRemoveButton = styled(Button)``;

const SearchRecentItem = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  font-size: var(--search-recent-item-font-size);
  font-weight: var(--search-recent-item-font-weight);
  line-height: var(--search-recent-item-line-height);
  padding: var(--search-recent-item-padding);
  color: var(--search-recent-item-text-color);
  cursor: pointer;

  ${SearchRecentRemoveButton} {
    display: none;
  }

  &:hover {
    background-color: var(--search-recent-item-bg-color-hover);
    color: var(--search-recent-item-text-color-hover);

    ${SearchRecentRemoveButton} {
      display: flex;
      padding: 0;
    }
  }

  &:focus-visible {
    outline: 1px solid var(--search-recent-item-border-color-focused);
    background-color: var(--search-recent-item-bg-color-active);
  }

  @media screen and (min-width: ${breakpoints.small}) {
    ${SearchRecentRemoveButton} {
      display: none;
    }
  }
`;

const SearchRecentItemWrapper = styled.div`
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
`;
