import { useState } from 'react';

export interface SortingOption {
  onClick?: () => void;
  value: string;
  label: string;
}

export const SortingFlyout = ({
  options,
  onChange,
  sortBy,
  ascending = false,
}: {
  options: SortingOption[];
  onChange: (sortBy: string, ascending: boolean) => void;
  sortBy: string;
  ascending: boolean;
}) => {
  const [_sortBy, setSortBy] = useState(sortBy);
  const [_ascending, setAscending] = useState(ascending);

  const handleClick = (value: string) => {
    const isAscending = value === _sortBy ? !_ascending : false;

    setAscending(isAscending);
    setSortBy(value);

    onChange(value, isAscending);
  };

  const renderArrow = (type: string) => {
    if (_sortBy === type) {
      return <span>{_ascending ? '↑' : '↓'}</span>;
    } else {
      return null;
    }
  };

  return (
    <div className="flyout" style={{ width: 140 }}>
      {options.map((option) => {
        return (
          <div
            className="flyout-item paddingX4 flex justifyBetween"
            style={{ fontWeight: option.value === _sortBy ? 'bold' : 'normal' }}
            onClick={() => handleClick(option.value)}
            key={option.value}
          >
            {option.label}
            {renderArrow(option.value)}
          </div>
        );
      })}
    </div>
  );
};
