// @flow
import React, { useState, useCallback } from 'react';
import type { FilterBarProps } from './filter-bar.proptypes';
import { FilterBarTab } from './filter-bar-tab';
import { Box } from '../../../primitives';

const useFilterBarState = ({ selectedValue, onChange }) => {
  const [selectedFilter, setSelectedFilter] = useState(selectedValue);

  const handleSwitchClicked = useCallback(
    (value) => (_e) => {
      if (typeof onChange === 'function') {
        onChange(value);
      }
      setSelectedFilter(value);
    },
    [onChange],
  );

  return { selectedFilter, handleSwitchClicked };
};

export const FilterBar = ({
  options = [],
  onChange,
  selectedValue,
  spacing,
  className,
  'data-qa': dataQa,
  'data-cy': dataCy,
  id,
}: FilterBarProps) => {
  const { selectedFilter, handleSwitchClicked } = useFilterBarState({
    selectedValue,
    onChange,
  });

  return (
    <Box
      spacing={spacing !== undefined ? spacing : ['pv2', 'ph3']}
      className={className}
      data-cy={dataCy}
      data-qa={dataQa}
      id={id}
    >
      {options.map(({ value, label }) => (
        <FilterBarTab
          key={value}
          label={label}
          selected={selectedFilter === value}
          onClick={handleSwitchClicked(value)}
        />
      ))}
    </Box>
  );
};

FilterBar.displayName = 'FilterBar';
