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

import type { JSX } from 'react';

import { useThemeConfig, useThemeHooks } from '@redocly/theme/core/hooks';
import { Button } from '@redocly/theme/components/Button/Button';
import { SearchIcon } from '@redocly/theme/icons/SearchIcon/SearchIcon';
import { breakpoints, getUserAgent } from '@redocly/theme/core/utils';

export type SearchTriggerProps = {
  onClick: () => void;
  className?: string;
};

export function SearchTrigger({ onClick, className }: SearchTriggerProps): JSX.Element {
  const themeSettings = useThemeConfig();
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();

  const defaultKeyShortcut = '⌘+K,CTRL+K';
  const keyShortcuts = themeSettings?.search?.shortcuts ?? [defaultKeyShortcut];
  let mainShortcutKey: string | null | undefined = null;

  if (keyShortcuts) {
    if (Array.isArray(keyShortcuts)) {
      mainShortcutKey = keyShortcuts[0];
    } else {
      mainShortcutKey = keyShortcuts;
    }
  }

  mainShortcutKey = mainShortcutKey?.toUpperCase();
  const isMac = getUserAgent().includes('Mac');

  return (
    <SearchTriggerWrapper
      onClick={onClick}
      className={className}
      data-component-name="Search/SearchTrigger"
    >
      <SearchTriggerButton
        data-testid="search-trigger-button"
        variant="text"
        size="medium"
        icon={<SearchIcon />}
        aria-label="Search trigger button"
      />
      <SearchTriggerInput
        data-testid="search-trigger-input"
        data-translation-key="search.navbar.label"
      >
        <SearchIcon />
        {translate('search.navbar.label', 'Search')}
        {mainShortcutKey === defaultKeyShortcut ? (
          <span>{isMac ? '⌘K' : 'Ctrl+K'}</span>
        ) : (
          <span>{mainShortcutKey}</span>
        )}
      </SearchTriggerInput>
    </SearchTriggerWrapper>
  );
}

const SearchTriggerWrapper = styled.div`
  color: var(--search-trigger-color);
  line-height: var(--search-trigger-line-height);

  svg {
    width: var(--search-trigger-icon-size);
    height: var(--search-trigger-icon-size);
  }
`;

const SearchTriggerButton = styled(Button)`
  display: inline-flex;

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

const SearchTriggerInput = styled.div`
  display: none;
  align-items: center;
  justify-content: center;
  gap: var(--search-trigger-gap);
  border: var(--search-trigger-border-width) var(--search-trigger-border-style)
    var(--search-trigger-border-color);
  border-radius: var(--search-trigger-border-radius);
  background: var(--search-trigger-bg-color);
  padding: var(--search-trigger-padding);

  &:hover {
    border-color: var(--search-trigger-border-color-hover);
  }

  @media screen and (min-width: ${breakpoints.medium}) {
    display: inline-flex;
  }
`;
