import * as React from 'react';
import SelectBox from "./SelectBox";
import {FILTER_TYPES} from "./constants";
import Badge from "../Badge/Badge";

const _ = require("lodash");


function Filter() {
    const [tags, setTags] = React.useState([]);

    const updateTags = e => {
        e.every(i => i.value)
            ? setTags(_.uniqBy([...tags.filter(tag => tag.group !== e[0].group), ...e], 'value'))
            : setTags(tags.filter(tag => tag.group !== e[0].group))
    }
    const removeItem = (e) => {
        setTags(tags.filter(tag => tag.value !== e.value));
    }

    const clearFilters = () => {
        setTags([]);
    }

    return <div className="filter">
        <div className="filter__list">
            {FILTER_TYPES.map((filter, i) => {
                return <SelectBox
                    key={i}
                    options={filter.values}
                    label={filter.group}
                    setValuesOutside={updateTags}
                    tags={tags}
                />
            })}
            <div className="filter__input-wrapper">
                <input
                    type="text"
                    className="filter__input"
                    placeholder="Search"
                />
            </div>
        </div>
        {tags.length
            ? <div className="filter__tags">
                {tags.map((tag, i) => <Badge tagObj={tag} onRemove={removeItem} key={i}/>)}
                <span className="filter__tags-close" onClick={clearFilters}>Clear All</span>
            </div>
            : null}
    </div>;
}

export default Filter;
