import cx from 'clsx';
import { isEqual, isNil } from 'lodash-es';
import { useCallback, useRef, useState } from 'react';
import type { Option } from '../models';
import styles from './HSegmentedControl.module.css';

type HSegmentedControlProps = {
  options?: Option[];
  value?: Option['value'];
  onChange?: (value: Option['value']) => void;
};

export function HSegmentedControl({ options = [], value, onChange }: HSegmentedControlProps) {
  const [selected, setSelected] = useState(value ?? options[0].value ?? null);
  const [sliderPosition, setSliderPosition] = useState(0);
  const [sliderWidth, setSliderWidth] = useState(0);
  const sliderRef = useRef<HTMLDivElement>(null);
  const optionsRef = useRef<HTMLDivElement[]>([]);

  const handleSelectAction = useCallback((option: Option['value'], index: number) => {
    setSelected(option);
    onChange?.(option);
    if (optionsRef.current && optionsRef.current.length > index) {
      const optionElement = optionsRef.current[index];
      setSliderPosition(optionElement.offsetLeft);
      setSliderWidth(optionElement.offsetWidth);
    }
  }, []);

  return (
    <div className={styles.segmented_control}>
      <div className={styles.options}>
        {options.map((option, index) => (
          <div
            key={`${index}_${option.value}`}
            className={cx(styles.option, isEqual(selected, option.value) && styles.selected)}
            ref={(el) => (optionsRef.current[index] = el!)}
            onClick={() => handleSelectAction(option.value, index)}>
            {option.label}
          </div>
        ))}
        {!isNil(selected) && (
          <div
            className={styles.slider}
            ref={sliderRef}
            style={{ left: `${sliderPosition}px`, width: `${sliderWidth}px` }}
          />
        )}
      </div>
    </div>
  );
}
