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

import type { CodeWalkthroughFilter } from '@redocly/config';

import { Tag, ContentWrapper as TagContentWrapper } from '@redocly/theme/components/Tag/Tag';

export type GetFilterState = (groupId: string) => { value: string; render: boolean } | null;
export type CodeFilterProps = {
  filters: CodeWalkthroughFilter[];
  getFilterState: GetFilterState;
  handleFilterSelect: (groupId: string, id: string) => void;
  filtersElementRef?: React.RefObject<HTMLDivElement>;
};

export function CodeFilters({
  filters,
  getFilterState,
  handleFilterSelect,
  filtersElementRef,
}: CodeFilterProps) {
  if (filters.length === 0) {
    return null;
  }

  return (
    <FilterWrapper
      ref={filtersElementRef}
      data-component-name="Markdoc/CodeWalkthrough/CodeFilters"
    >
      {filters.map(({ label, items, id }) => {
        return (
          <Filter key={id}>
            {label && <FilterName>{label}:</FilterName>}
            <ButtonsWrapper>
              {items?.map((item) => (
                <TagButton
                  size="large"
                  borderless
                  active={getFilterState(id)?.value === item.value}
                  key={item.value}
                  onClick={() => handleFilterSelect(id, item.value)}
                >
                  {item.value}
                </TagButton>
              ))}
            </ButtonsWrapper>
          </Filter>
        );
      })}
    </FilterWrapper>
  );
}

const Filter = styled.div`
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-xs);
  max-width: 100%;
`;

const FilterName = styled.div`
  color: var(--color-text-primary);
  font-size: var(--font-size-base);
`;

const FilterWrapper = styled.div`
  --tag-text-transform: none;
  display: flex;
  flex-direction: row;
  gap: var(--spacing-sm);
  flex-wrap: wrap;
  position: sticky;

  padding-top: calc(var(--spacing-xs) + var(--spacing-xl));
  padding-right: var(--spacing-xl);
  padding-left: var(--spacing-xl);
  padding-bottom: var(--spacing-xs);
  top: calc(var(--navbar-height));
  background-color: var(--bg-color);
  z-index: 1;
  max-width: var(--md-content-max-width);
`;

const ButtonsWrapper = styled.div`
  display: flex;
  min-width: 0;
  flex-wrap: wrap;
`;

const TagButton = styled(Tag)`
  cursor: pointer;
  padding: 0px var(--spacing-xs);
  margin-right: var(--spacing-xs);
  max-width: 100%;
  margin-bottom: var(--spacing-xs);

  ${TagContentWrapper} {
    display: inline-block;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
  }
`;
