import React, { useRef, useEffect, useState } from "react";
import "./segment-styles.scss";

export interface SegmentOption {
  label: string;
  value: string;
}

interface SegmentProps {
  options: SegmentOption[];
  value: string;
  onChange: (value: string) => void;
}

const Segment: React.FC<SegmentProps> = ({ options, value, onChange }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [indicatorStyle, setIndicatorStyle] = useState<React.CSSProperties>({});

  useEffect(() => {
    if (!containerRef.current) return;

    const buttons =
      containerRef.current.querySelectorAll<HTMLButtonElement>(
        ".segment__option"
      );
    const activeButton = Array.from(buttons).find(
      (btn) => btn.dataset.value === value
    );

    if (activeButton) {
      const { offsetLeft, offsetWidth } = activeButton;
      setIndicatorStyle({
        left: offsetLeft,
        width: offsetWidth,
      });
    }
  }, [value, options]);

  return (
    <div className="segment" ref={containerRef}>
      <div className="segment__indicator" style={indicatorStyle} />
      {options.map((option) => (
        <button
          key={option.value}
          type="button"
          className={`segment__option ${
            value === option.value ? "segment__option--active" : ""
          }`}
          data-value={option.value}
          onClick={() => onChange(option.value)}
        >
          {option.label}
        </button>
      ))}
    </div>
  );
};

export default Segment;
