import React, { useEffect, useState } from 'react';
import { twMerge } from 'tailwind-merge';

interface TabSelectorProps {
  selections: { name: string; key: string }[];
  onChange: (key: string) => void;
  initialSelection?: string;
  selectorButtonClassName?: string;
}

const TabSelector: React.FC<TabSelectorProps> = ({
  selections,
  onChange,
  initialSelection,
  selectorButtonClassName,
}) => {
  const [selectedKey, setSelectedKey] = useState(selections?.[0]?.key);

  useEffect(() => {
    setSelectedKey(initialSelection || selections?.[0]?.key);
  }, [initialSelection]);

  const handleTabClick = (key: string) => {
    setSelectedKey(key);
    onChange(key);
  };

  return (
    <div className='inline-flex gap-[8px] font-sans'>
      {selections.map((selection) => (
        <button
          key={selection.key}
          className={twMerge(
            'shrink-0 cursor-pointer rounded-[100px] px-[12px] py-[10px] text-[14px] leading-[20px] font-normal transition-colors duration-200',
            selectedKey === selection.key
              ? 'border border-border-primary bg-foreground-primary text-background-primary'
              : 'border border-border-primary bg-background-secondary text-foreground-primary hover:text-foreground-secondary',
            selectorButtonClassName
          )}
          onClick={() => handleTabClick(selection.key)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              handleTabClick(selection.key);
            }
          }}
        >
          {selection.name}
        </button>
      ))}
    </div>
  );
};

export default TabSelector;
