'use client';

import { ButtonHTMLAttributes } from 'react';

interface SegmentedControlOption {
  value: string;
  label: string;
  description?: string;
  disabled?: boolean;
}

interface SegmentedControlProps {
  options: SegmentedControlOption[];
  value: string;
  onChange?: (value: string) => void;
}

export default function SegmentedControl({
  options,
  value,
  onChange,
}: SegmentedControlProps) {
  const handleSelect = (optionValue: string, optionDisabled?: boolean) => {
    if (!onChange || optionDisabled) return;
    if (optionValue === value) return;
    onChange(optionValue);
  };

  return (
    <div className="inline-flex w-full flex-wrap gap-2 rounded-full bg-iron-gray/60 px-1 py-1">
      {options.map((option) => {
        const isSelected = option.value === value;
        const baseClasses =
          'flex-1 min-w-[140px] px-3 py-1.5 text-xs font-medium rounded-full transition-colors text-left';
        const selectedClasses = isSelected
          ? 'bg-primary-blue text-white'
          : 'text-gray-300 hover:text-white hover:bg-charcoal-outline/80';
        const disabledClasses = option.disabled
          ? 'opacity-50 cursor-not-allowed hover:bg-transparent hover:text-gray-300'
          : '';

        const buttonProps: ButtonHTMLAttributes<HTMLButtonElement> = {
          type: 'button',
          onClick: () => handleSelect(option.value, option.disabled),
          'aria-pressed': isSelected,
          disabled: option.disabled,
        };

        return (
          <button
            key={option.value}
            {...buttonProps}
            className={`${baseClasses} ${selectedClasses} ${disabledClasses}`}
          >
            <div className="flex flex-col items-start">
              <span>{option.label}</span>
              {option.description && (
                <span className="mt-0.5 text-[10px] text-gray-400">
                  {option.description}
                </span>
              )}
            </div>
          </button>
        );
      })}
    </div>
  );
}