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

import type { ForwardedRef, ReactElement } from 'react';
import type { SegmentedProps } from '@redocly/theme/core/types';

import { typedMemo } from '@redocly/theme/core/hoc/typed-memo';

function SegmentedComponent<T>(
  { options, onChange, value, className = '', size = 'regular' }: SegmentedProps<T>,
  ref?: ForwardedRef<HTMLDivElement>,
): ReactElement {
  return (
    <SegmentedGroup
      ref={ref}
      data-component-name="Segmented/Segmented"
      className={`tag-grey ${size} ${className}`}
      role="tablist"
    >
      {options.map((opt, index) => (
        <React.Fragment key={index}>
          {opt.divider}
          <SegmentedItem
            key={opt.label}
            role="tab"
            title={opt.label}
            onClick={() => onChange(opt)}
            $isActive={value == opt.value}
            $size={size}
          >
            {opt.element || opt.label}
          </SegmentedItem>
        </React.Fragment>
      ))}
    </SegmentedGroup>
  );
}

export const Segmented = typedMemo(forwardRef(SegmentedComponent)) as <T>(
  props: SegmentedProps<T> & { ref?: ForwardedRef<HTMLDivElement> },
) => ReactElement;

const SegmentedGroup = styled.div`
  display: flex;
  background: var(--segmented-buttons-bg-color-main);
  padding: calc(var(--spacing-xxs) / 2);
  gap: calc(var(--spacing-xxs) / 2);
  border-radius: var(--border-radius-md);
  max-width: 100%;
  width: fit-content;
`;

const SegmentedItem = styled.button<{ $isActive: boolean; $size: string }>`
  ${({ $size }) =>
    $size === 'small' &&
    css`
      --segmented-font-size: var(--font-size-sm);
      --segmented-font-size-active: var(--font-size-sm);
      --segmented-line-height: var(--line-height-sm);
    `}

  ${({ $isActive }) =>
    $isActive
      ? css`
          font-size: var(--segmented-font-size-active);
          font-weight: var(--segmented-font-weight-active);
          background: var(--segmented-buttons-bg-color-inner);
          color: var(--segmented-text-color-active);
          cursor: default;
        `
      : css`
          font-size: var(--segmented-font-size);
          font-weight: var(--segmented-font-weight);
          color: var(--segmented-text-color);
          cursor: pointer;
        `}
  line-height: var(--segmented-line-height);
  border-radius: var(--border-radius);
  padding: ${({ $size }) => ($size === 'small' ? 0 : '3px')} var(--spacing-sm);
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
`;
