import { View } from "@tarojs/components";
import { isEqual } from "lodash";
import { Checkbox } from "@taroify/core";
import { useState, useEffect } from "react";
const FormCheckbox = (props) => {
  const { value, onChange, options } = props;

  const [selected, setSelected] = useState([]);

  useEffect(() => {
    if (typeof value === "object" && !isEqual(value, selected)) {
      setSelected(value);
    }
  }, [value]);

  if (!options || options.length === 0) {
    return (
      <Checkbox
        shape="square"
        checked={value}
        onChange={(e: any) => onChange(e.target.value)}
      ></Checkbox>
    );
  }

  let optionTemp = [...options];
  optionTemp = optionTemp.map((v) => {
    if (typeof v === "string") return { label: v, value: v };
    return v;
  });

  return (
    <View style={{ width: "100%" }}>
      <Checkbox.Group
        value={selected}
        onChange={(e: any) => {
          setSelected(e);
          onChange(e.join(","));
        }}
      >
        {optionTemp.map((item) => {
          return (
            <Checkbox name={item.value} shape="square">
              {item.label}
            </Checkbox>
          );
        })}
      </Checkbox.Group>
    </View>
  );
};

export default FormCheckbox;
