import React, { useRef, useState, useEffect } from "react";
import { without } from "lodash";
import { InputHandlers } from "../dropdown/dropdown";
import Select, { ISelect } from "./select";
import MultiselectItem from "./multiselect-item";

interface IItem {
  id: string | number;
  text: string;
}

interface IMultiSelect extends ISelect {
  onSubmit: (selectedItems: IItem["id"][]) => void;
  onCancel?: () => void;
  cancelText?: string;
  submitText?: string;
  items: IItem[];
  value: IItem["id"][] | null;
}

const MultiSelect = (props: IMultiSelect) => {
  const { value, items, onSubmit, onCancel, cancelText, submitText, onClose, ...rest } = props;
  const actionsRef = useRef<InputHandlers>(null);
  const [selectedItems, setSelectedItems] = useState<IItem["id"][]>([]);

  useEffect(() => {
    setSelectedItems(value || []);
  }, [value]);

  const controls = (
    <div className="mt-3 mb-3 d-flex">
      <button
        className="btn btn-sm btn-link flex-fill mx-3"
        onClick={() => {
          if (actionsRef.current) {
            actionsRef.current.closeDropdown();
          }
          onCancel && onCancel();
        }}
      >
        {cancelText}
      </button>
      <button
        className="btn btn-sm btn-primary flex-fill mr-3"
        onClick={() => {
          if (actionsRef.current) {
            actionsRef.current.closeDropdown();
          }
          onSubmit && onSubmit(selectedItems);
        }}
      >
        {submitText}
      </button>
    </div>
  );

  return (
    <Select
      ref={actionsRef}
      controls={controls}
      onClose={() => {
        setSelectedItems(value || []);
        onClose && onClose();
      }}
      {...rest}
    >
      {items.map(i => {
        const isActive = selectedItems.indexOf(i.id) !== -1;
        return (
          <MultiselectItem
            key={i.id}
            title={i.text}
            isActive={isActive}
            onClick={() => {
              if (isActive) {
                // deselect
                setSelectedItems(without(selectedItems, i.id));
              } else {
                // select
                setSelectedItems([...selectedItems, i.id]);
              }
            }}
          >
            {i.text}
          </MultiselectItem>
        );
      })}
    </Select>
  );
};

MultiSelect.displayName = "MultiSelect";
MultiSelect.defaultProps = {
  cancelText: "Cancel",
  submitText: "Apply"
};

export default MultiSelect;
