import {
  FieldValues,
  Path,
  useController,
  useFormContext,
  useWatch,
} from "react-hook-form";

export function CheckboxesGroup<IFieldValues extends FieldValues>({
  options,
  name,
}: {
  options: string[];
  name: Path<IFieldValues>;
}) {
  const { control } = useFormContext<IFieldValues>();

  const {
    field: { ref, onChange, ...inputProps },
  } = useController({ control, name });

  const values: string[] = useWatch({ control, name });

  return (
    <div className="flex flex-wrap lg:gap-[0.556vw] gap-2">
      {options.map((option) => (
        <label
          htmlFor={name + "_" + option}
          key={option}
          className={`cursor-pointer transition-colors lg:rounded-[1.111vw] rounded-2xl font-medium text-nowrap select-none lg:px-[1.667vw] px-6 lg:py-[1.181vw] py-[17px] btnm ${
            values.includes(option)
              ? "bg-white text-black"
              : "bg-[#37393B99] hover:bg-[#37393B]"
          }`}
        >
          {option}
          <input
            id={name + "_" + option}
            className="hidden"
            type="checkbox"
            {...inputProps}
            checked={values.includes(option)}
            ref={ref}
            onChange={() => {
              onChange(
                values.includes(option)
                  ? values.filter((x) => x !== option)
                  : [...values, option]
              );
            }}
          />
        </label>
      ))}
    </div>
  );
}
