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

import { AscSortIcon } from '@redocly/theme/icons/AscSortIcon/AscSortIcon';
import { DescSortIcon } from '@redocly/theme/icons/DescSortIcon/DescSortIcon';
import { Dropdown } from '@redocly/theme/components/Dropdown/Dropdown';
import { DropdownMenu } from '@redocly/theme/components/Dropdown/DropdownMenu';
import { DropdownMenuItem } from '@redocly/theme/components/Dropdown/DropdownMenuItem';
import { useThemeHooks } from '@redocly/theme/core/hooks';

export type CatalogSortButtonProps = {
  onSortChange: (sortOption: string | null) => void;
  currentSort?: string | null;
};

export function CatalogSortButton({
  onSortChange,
  currentSort,
}: {
  onSortChange: (sortOption: string | null) => void;
  currentSort?: string | null;
}) {
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();

  const toggleSort = useCallback(
    (field: string): void => {
      const newSort = currentSort === `-${field}` ? field : `-${field}`;
      onSortChange(newSort);
    },
    [currentSort, onSortChange],
  );

  return (
    <div data-component-name="Catalog/CatalogSortButton">
      <Dropdown
        trigger={
          <SortTrigger>
            <SortIconWrapper>
              {currentSort === '-title' ? <DescSortIcon /> : <AscSortIcon />}
            </SortIconWrapper>
            <SortText>{translate('catalog.sort', 'Sort')}</SortText>
          </SortTrigger>
        }
        alignment="end"
      >
        <DropdownMenu>
          <DropdownMenuItem onAction={() => toggleSort('title')}>
            {currentSort === '-title' ? 'Title | A → Z' : 'Title | Z → A'}
          </DropdownMenuItem>
        </DropdownMenu>
      </Dropdown>
    </div>
  );
}

const SortTrigger = styled.div`
  display: flex;
  align-items: center;
  gap: var(--catalog-sort-trigger-gap);
  padding: var(--catalog-sort-trigger-padding);
  border-radius: var(--catalog-sort-trigger-border-radius);
  cursor: pointer;
  &:hover {
    background-color: var(--catalog-sort-trigger-hover-bg-color);
  }
`;

const SortIconWrapper = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--catalog-sort-icon-color);
`;

const SortText = styled.span`
  font-size: var(--catalog-sort-text-font-size);
  color: var(--catalog-sort-text-color);
  font-weight: var(--catalog-sort-text-font-weight);
`;
