import React, { useState, JSX } from 'react';
import styled from 'styled-components';
import { useNavigate } from 'react-router-dom';

import { Accordion } from '@redocly/theme/components/Accordion/Accordion';
import { Select } from '@redocly/theme/components/Select/Select';
import { CatalogSwitcherItem } from '@redocly/theme/core/types';
import { getPathPrefix } from '@redocly/theme/core/utils';
import { useThemeHooks } from '@redocly/theme/core/hooks';
import { ChevronDownIcon } from '@redocly/theme/icons/ChevronDownIcon/ChevronDownIcon';

export type CatalogSelectorProps = {
  catalogSwitcherItems: CatalogSwitcherItem[];
  onChange: () => void;
};

export function CatalogSelector({
  catalogSwitcherItems,
  onChange,
}: CatalogSelectorProps): JSX.Element {
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();
  const [isExpanded, setIsExpanded] = useState(true);

  const navigate = useNavigate();
  const pathPrefix = getPathPrefix();

  const options = catalogSwitcherItems.map((item) => ({
    value: item.slug,
    element: translate(item.labelTranslationKey),
    label: translate(item.labelTranslationKey),
  }));

  const selectedCatalogItem = catalogSwitcherItems.find((item) => item.selected);

  const headerLabel = translate('catalog.catalogs.label', 'Catalogs');

  return (
    <CatalogSelectWrapper data-component-name="Catalog/CatalogSelector">
      <Accordion expanded={isExpanded} header={headerLabel} onToggle={setIsExpanded}>
        <CatalogSelect
          value={selectedCatalogItem?.slug}
          options={options}
          onChange={(value) => {
            navigate(`${pathPrefix}/catalogs/${value}`);
            onChange();
          }}
          icon={<ChevronDownIcon color="var(--catalog-select-icon-color)" />}
        />
      </Accordion>
    </CatalogSelectWrapper>
  );
}

export const CatalogSelectWrapper = styled.div`
  display: flex;
  flex-direction: column;
  gap: var(--filter-group-gap);
  --accordion-body-padding: var(--catalog-select-accordion-body-padding);
  --accordion-header-padding: var(--catalog-select-accordion-header-padding);
  --select-line-height: var(--catalog-select-select-line-height);
  --select-input-padding: var(--catalog-select-select-input-padding);
`;

export const CatalogSelect = styled(Select)`
  border-radius: var(--catalog-select-border-radius);
`;
