import { Button } from '@douyinfe/semi-ui';
import type { KeyboardEvent, ReactNode } from 'react';

export type SegmentedTabItem<Key extends string> = {
  key: Key;
  label: ReactNode;
  icon?: ReactNode;
  count?: number;
};

type SegmentedTabsProps<Key extends string> = {
  ariaLabel: string;
  value: Key;
  items: readonly SegmentedTabItem<Key>[];
  onChange: (key: Key) => void;
  className?: string;
  variant?: 'filled' | 'line';
};

export function SegmentedTabs<Key extends string>({
  ariaLabel,
  value,
  items,
  onChange,
  className = '',
  variant = 'line'
}: SegmentedTabsProps<Key>) {
  const selectFromKeyboard = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
    let nextIndex = index;
    if (event.key === 'ArrowRight') nextIndex = (index + 1) % items.length;
    else if (event.key === 'ArrowLeft') nextIndex = (index - 1 + items.length) % items.length;
    else if (event.key === 'Home') nextIndex = 0;
    else if (event.key === 'End') nextIndex = items.length - 1;
    else return;
    event.preventDefault();
    onChange(items[nextIndex].key);
    const tabs = event.currentTarget.parentElement?.querySelectorAll<HTMLElement>('[role="tab"]');
    window.requestAnimationFrame(() => tabs?.[nextIndex]?.focus());
  };

  return <div className={`v2-segmented-tabs is-${variant}${className ? ` ${className}` : ''}`} role="tablist" aria-label={ariaLabel}>
    {items.map((item, index) => {
      const selected = item.key === value;
      return <Button
        className={selected ? 'is-active' : ''}
        theme={variant === 'filled' && selected ? 'solid' : 'borderless'}
        type={selected ? 'primary' : 'tertiary'}
        size="small"
        role="tab"
        aria-selected={selected}
        tabIndex={selected ? 0 : -1}
        onKeyDown={(event) => selectFromKeyboard(event, index)}
        onClick={() => onChange(item.key)}
        key={item.key}
      >
        <span className="v2-segmented-tab-label">{item.icon}<span>{item.label}</span>{item.count != null ? <em className="v2-segmented-tab-count">{item.count}</em> : null}</span>
      </Button>;
    })}
  </div>;
}
