import { useState } from 'react';
import { useFormContext } from 'react-hook-form';

import { Text } from 'components/common';

export const MultiselectFilter = ({
  options,
  max = 5,
}: {
  options: { value: string; label: string; name: string }[];
  max: number;
}) => {
  const { register } = useFormContext();

  const hideItems = max && options.length > max;
  const [hidden, setHidden] = useState(hideItems);

  return (
    <div>
      <div className="oh">
        {options.slice(0, hidden ? max : Infinity).map((item) => {
          return (
            <label
              className="flex alignCenter justifyBetween paddingX3 spacing2 cup hover1"
              style={{ height: 32, lineHeight: '32px' }}
              key={item.value}
            >
              <Text size="s" truncate>
                {item.label}
              </Text>
              <input
                type="checkbox"
                value={item.value}
                {...register(item.name)}
              />
            </label>
          );
        })}
        {/* react-hook-form false checkbox workaround */}
        {/* https://github.com/react-hook-form/react-hook-form/issues/476#issuecomment-553849830 */}
        {options.length === 1 && (
          <input type="checkbox" {...register(options[0].name)} hidden />
        )}
      </div>
      {hideItems && (
        <div
          className="paddingX3 paddingY2 fz14 c-blue cup"
          onClick={() => setHidden((s) => !s)}
        >
          {hidden ? 'Show more' : 'Show less'}
        </div>
      )}
    </div>
  );
};
