import React from 'react';
import FormCheck from 'react-bootstrap/esm/FormCheck';
import FormCheckInput from 'react-bootstrap/esm/FormCheckInput';
import FormCheckLabel from 'react-bootstrap/esm/FormCheckLabel';

// Helper function to convert array to object with values as keys
const _keyBy = (arr: string[]) => {
  return arr.reduce((acc, val) => {
    acc[val] = val;
    return acc;
  }, {} as { [key: string]: string });
};

// Define a TypeScript interface for your component's props
interface CheckboxGroupProps {
  data: Array<{ id: string; name: string; disabled?: boolean }>;
  name?: string;
  value: string[];
  type: 'list' | 'inline' | 'stack';
  onChange?: (values: string[], event: React.ChangeEvent<HTMLInputElement>) => void;
  inline?: boolean;
  flush?: boolean;
}

let CheckboxGroup: React.FC<CheckboxGroupProps> =  ({ flush=false, inline=false, type='list', data=[], name='', value=[], onChange=()=>{}, ...props }) => {
  let objectValue = React.useMemo(() => _keyBy(value), [value]);

  const handleOnClick = (id: string) => (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = { ...objectValue };
    
    if (newValue[id]) {
      delete newValue[id];
    } else {
      newValue[id] = id;
    }
    
    onChange(Object.values(newValue), e);
  }

if (flush === true){var listclass="list-group list-group-flush"} else {var listclass="list-group"};
  if ( type === 'list' ){
    return (
      <ul className={listclass}>
        {
          data.map(item => (
            <li key={item.id} className="list-group-item">
              <FormCheck
                id={item.id}
                inline={false}
                {...props}>
                  <FormCheckInput
                    type="checkbox"
                    id={item.id}
                    className="me-2"
                    checked={!!objectValue[item.id]}
                    onChange={handleOnClick(item.id)}
                    disabled={item.disabled}
                  />                
                  <FormCheckLabel
                    htmlFor={item.id}
                    className="stretched-link"
                  >{item.name}
                  </FormCheckLabel>
              </FormCheck>
            </li>
          ))
        }
      </ul>
    );
  } else {
    if ( type === 'inline' ){inline = true} else {inline = false};
    return (
      <div className="mb-3">
        {
          data.map(item => (
            <FormCheck
              key={item.id}
              id={item.id}
              label={item.name}
              inline={inline}
              name={name}
              disabled={item.disabled}
              checked={!!objectValue[item.id]}
              onChange={handleOnClick(item.id)}
              {...props}
            />
          ))
        }
      </div>
    );
  };
};

CheckboxGroup = React.memo(CheckboxGroup)

export default CheckboxGroup;
export { CheckboxGroup, CheckboxGroupProps };