import { type SxProps, type Theme } from '@material-hu/mui/styles';
import ToggleButtonGroup from '@material-hu/mui/ToggleButtonGroup';

import SegmentedToggleItem from './SegmentedToggleItem';

export type SegmentedToggleOption<T extends string | number> = {
  value: T;
  label: string;
  tooltip?: string | null;
  color?: string;
};

export type SegmentedToggleProps<T extends string | number> = {
  options: SegmentedToggleOption<T>[];
  value: T | null;
  onChange: (value: T | null) => void;
  exclusive?: boolean;
  activeColor?: string;
  ariaLabel?: string;
  sx?: SxProps<Theme>;
  showCheckWhenSelected?: boolean;
};

export default function SegmentedToggle<T extends string | number>({
  options,
  value,
  onChange,
  exclusive = true,
  activeColor,
  ariaLabel,
  sx,
  showCheckWhenSelected = false,
}: SegmentedToggleProps<T>) {
  const handleToggleChange = (_: unknown, newValue: T | null) => {
    onChange(newValue);
  };

  return (
    <ToggleButtonGroup
      exclusive={exclusive}
      value={value}
      onChange={handleToggleChange}
      aria-label={ariaLabel}
      sx={sx}
    >
      {options.map(option => (
        <SegmentedToggleItem
          key={String(option.value)}
          option={option}
          isSelected={value === option.value}
          activeColor={activeColor}
          showCheckWhenSelected={showCheckWhenSelected}
        />
      ))}
    </ToggleButtonGroup>
  );
}
