import React, { FC, useState, useEffect } from "react";

import {PillsGroupProps} from "./PillsGroup.types"
import { Pill } from "./index";
//import { useEffect } from "@storybook/addons";


export const PillsGroup: FC<PillsGroupProps> = ({
    options = [
        {id: "1", label: "itemTest 5", color: "#fee" },
        {id: "2", label: "itemTest 2", color: "#afe" }
    ],
	label,
    style = {},
	multiple = false,
	values = [],
	disabled = false,
	size = "dynamic",
	multicolor = false,
	onChange,
	onClick,
	icon = "",
    onClickIcon
}) => {

	return (
		<div className="pillsGroup-gtc-rc-wrap-div">
			{label && <div className="pills-group-gtc-rc-label">{label}</div>}
			<div className="pillsGroup-gtc-rc-div">
				{options &&
					options.length > 0 &&
					options.map((item:any, index) => {
						let selected = values ? values.find((selectedItem:any) => {
							return selectedItem?.id === item?.id;
						}) : null;

						let newItem: any = { ...item };
						if (!multicolor) {
							newItem = { ...item, color: "default-green" };
							if (multiple) {
								newItem = { ...newItem, color: "default-blue"};
							}
	
							if (!selected) {
								newItem = { ...newItem, color: "default"};
							}
						}

						return (
							<Pill
								key={index}
								item={newItem}
                                variant={!multicolor ? "filled" : (selected ? "filled" : "outlined")}
								size={size}
                                style={style}
								clickable={true}
								disabled={disabled}
								icon={icon}
   								onClickIcon={() => {
									if (onClickIcon) onClickIcon(item);
								}}
								onClick={(item) => {
									let newValue:any = [];

									if (multiple && item?.id != -1 && item?.id != 0) {
										if (selected) {
											newValue = values.filter(
												(selectedItem:any) => selectedItem?.id != item?.id && selectedItem?.id != -1 && selectedItem?.id != 0,
											);
										} else {
											newValue = newValue.concat(values, item);
											newValue = newValue.filter((newSelectedItem:any) => newSelectedItem?.id != -1 && newSelectedItem?.id != 0);
										}
									} else {
										newValue = [item];
									}

									if (onChange) {
										onChange(newValue);
									}

									if (onClick) {
										onClick(item)
									}
								}}
							/>
						);
					})}
			</div>
		</div>
	);
};