import React, { JSX } from 'react';
import styled, { css } from 'styled-components';

import { CatalogViewMode } from '@redocly/theme/core/types';
import { FilterInput } from '@redocly/theme/components/Filter/FilterInput';
import { CatalogSortButton } from '@redocly/theme/components/Catalog/CatalogSortButton';
import { CatalogViewModeToggle } from '@redocly/theme/components/Catalog/CatalogViewModeToggle';
import { breakpoints } from '@redocly/theme/core';

export type CatalogActionsRowProps = {
  searchQuery: string;
  setSearchQuery: (updatedTerm: string) => void;
  sortOption: string | null;
  setSortOption: (option: string | null) => void;
  viewMode?: CatalogViewMode;
  onViewModeChange?: (mode: CatalogViewMode) => void;
  isDetailsPage?: boolean;
};

export function CatalogActionsRow({
  searchQuery,
  setSearchQuery,
  sortOption,
  setSortOption,
  viewMode,
  onViewModeChange,
  isDetailsPage = false,
}: CatalogActionsRowProps): JSX.Element {
  return (
    <CatalogActionsRowWrapper isDetailsPage={isDetailsPage}>
      <CatalogSearchInputWrapper>
        <FilterInput
          value={searchQuery}
          onChange={(updatedTerm) => setSearchQuery(updatedTerm)}
          dataTestId="catalog-search-input"
        />
      </CatalogSearchInputWrapper>

      <CatalogControlsWrapper>
        {viewMode === 'cards' && (
          <CatalogSortButton onSortChange={setSortOption} currentSort={sortOption} />
        )}
        {viewMode && onViewModeChange && (
          <CatalogViewModeToggle viewMode={viewMode} onViewModeChange={onViewModeChange} />
        )}
      </CatalogControlsWrapper>
    </CatalogActionsRowWrapper>
  );
}

export const CatalogActionsRowWrapper = styled.div<{ isDetailsPage: boolean }>`
  display: flex;
  align-items: center;

  margin-bottom: ${({ isDetailsPage }) => (isDetailsPage ? 'var(--spacing-sm)' : 'var(--spacing-xl)')};
  

  ${({ isDetailsPage }) =>
    !isDetailsPage &&
    css`
    @media screen and (max-width: ${breakpoints.medium}) {
      display: none;
    }
  `}
`;

export const CatalogControlsWrapper = styled.div`
  display: var(--catalog-controls-wrapper-display);
  align-items: var(--catalog-controls-wrapper-align-items);
  margin-left: var(--catalog-controls-wrapper-margin-left);
  gap: var(--catalog-controls-wrapper-gap);
`;

export const CatalogSearchInputWrapper = styled.div`
  width: var(--catalog-search-input-wrapper-width);
`;
