import React, { useEffect, useState } from 'react';

export interface ICheckItems {
  label: string;
  value: string;
}

export interface ICheckProps {
  items: ICheckItems[];
  onChange: (selectedValues: IChecklistSelectedValues) => void;
}

export interface IChecklistSelectedValues {
  [label: string]: boolean;
}

export const CheckButton: React.FC<ICheckProps> = ({ items, onChange }) => {
  const generateSelectedValuesList = () => {
    const selectedValues: IChecklistSelectedValues = {};

    items.forEach(item => {
      selectedValues[item.label] = false;
    });

    return selectedValues;
  };

  const [selectedValues, setSelectedValues] = useState<
    IChecklistSelectedValues
  >(generateSelectedValuesList());

  const handleClick = (label: string) => {
    setSelectedValues({
      ...selectedValues,
      [label]: !selectedValues[label],
    });
  };

  useEffect(() => {
    if (selectedValues) {
      onChange(selectedValues);
    }
  }, [selectedValues]);

  return (
    <div id="elemento-checkbox">
      {items?.map((element, index) => {
        return (
          <div key={`${element.label}_${index}`}>
            <input
              className="rpgui-checkbox"
              type="checkbox"
              checked={selectedValues[element.label]}
              onChange={() => {}}
            />
            <label onPointerDown={() => handleClick(element.label)}>
              {element.label}
            </label>
            <br />
          </div>
        );
      })}
    </div>
  );
};
