import React, { FC, useEffect, useState } from "react";
import { Checkbox } from ".";
import { CheckGroupProps } from "./CheckGroup.types";

const CheckGroup: FC<CheckGroupProps> = ({ list, onChange, value, labelDir, isDisabled }) => {
  const [checkedState, setCheckedState] = useState(
    new Array(list.length).fill(false)
  );

  useEffect(() => {
    if (!value) {
      setCheckedState(Array(list.length).fill(false));
    }
  }, [value]);

  const handleOnChange = (position: any) => {
    const updatedCheckedState = checkedState.map((item: any, index: any) =>
      index === position ? !item : item
    );
    setCheckedState(updatedCheckedState);
    onChange && onChange(updatedCheckedState);
  };

  return (
    <div style={{
        display: 'flex',
        width: '100%',
        flexDirection: labelDir
    }}>
      {list.map(({ label, value, id }: any, index: any) => (
        <Checkbox
          key={index}
          id={id}
          label={label}
          value={value}
          checked={checkedState[index]}
          isDisabled={isDisabled}
          onChange={() => handleOnChange(index)}
        />
      ))}
    </div>
  );
};

export default CheckGroup;
