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

import type { JSX } from 'react';

import { useThemeHooks, useSuggestedPages } from '@redocly/theme/core/hooks';
import { RecentlyViewedIcon } from '@redocly/theme/icons/RecentlyViewedIcon/RecentlyViewedIcon';
import { Link } from '@redocly/theme/components/Link/Link';

export type SearchSuggestedPagesProps = {
  className?: string;
};

export function SearchSuggestedPages({ className }: SearchSuggestedPagesProps): JSX.Element | null {
  const pages = useSuggestedPages();
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();
  if (!pages.length) return null;

  return (
    <SearchSuggestedWrapper data-component-name="Search/SearchSuggestedPages" className={className}>
      <SearchSuggestedTitle data-translation-key="search.suggested">
        {translate('search.suggested', 'Suggested pages')}
      </SearchSuggestedTitle>
      <SearchSuggestedItems>
        {pages.map((page) =>
          page.link ? (
            <SearchSuggestedItem key={page.label} to={page.link} {...page}>
              <SearchSuggestedItemWrapper>
                <RecentlyViewedIcon color="--search-item-text-color" />
                {page.label}
              </SearchSuggestedItemWrapper>
            </SearchSuggestedItem>
          ) : null,
        )}
      </SearchSuggestedItems>
    </SearchSuggestedWrapper>
  );
}

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

const SearchSuggestedTitle = styled.div`
  color: var(--search-suggested-item-title-text-color);
  font-size: var(--search-suggested-item-title-font-size);
  font-weight: var(--search-suggested-item-title-font-weight);
  line-height: var(--search-suggested-item-title-line-height);
  padding: var(--search-suggested-item-title-padding);
`;

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

const SearchSuggestedItem = styled(Link)`
  width: 100%;
  text-decoration: none;
  font-size: var(--search-suggested-item-font-size);
  font-weight: var(--search-suggested-item-font-weight);
  line-height: var(--search-suggested-item-line-height);
  color: var(--search-suggested-item-text-color);
  padding: var(--search-suggested-item-padding);
  cursor: pointer;

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

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

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