import { useState } from 'react';
import * as stylex from '@stylexjs/stylex';

import { Layout } from '~/src/ui/layouts/layout';
import { Clickable } from '~/src/ui/primitives/clickable';
import { styles } from './styles';

interface SegmentedButtonProps<T extends string> {
  options: { value: T; label: string }[];
  onChange?: (value: T) => void;
  defaultValue?: T;
}

export const SegmentedButton = <T extends string>({
  defaultValue,
  options,
  onChange,
}: SegmentedButtonProps<T>) => {
  const [value, setValue] = useState<T>(defaultValue ?? options[0].value);

  return (
    <div {...stylex.props(styles.container)}>
      <Layout align="center">
        {options.map((option) => {
          const isActive = option.value === value;

          return (
            <Clickable
              key={option.value}
              onClick={() => {
                setValue(option.value);
                onChange?.(option.value);
              }}
            >
              <div {...stylex.props(styles.option, isActive && styles.active)}>
                {option.label}
              </div>
            </Clickable>
          );
        })}
      </Layout>
    </div>
  );
};
