/* eslint-disable react-hooks/exhaustive-deps */
import clsx from 'clsx';
import { forwardRef, useEffect, useId, useState } from 'react';
import { useFormContext, UseFormRegister } from 'react-hook-form';
type CheckBoxProps = {
  value: any;
  label: string | React.ReactNode;
  classStr?: string;
  labelClassStr?: string;
  readOnly?: boolean;
  isSelectAll?: boolean;
  onClick?: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
} & ReturnType<UseFormRegister<any>>;

export const CheckBox = forwardRef<HTMLInputElement, CheckBoxProps>(function CheckBox(
  { name, labelClassStr, classStr, label, readOnly, onChange, onBlur, disabled, value: _value, isSelectAll },
  ref,
) {
  const {
    setValue,
    watch,
    formState: { errors },
  } = useFormContext();

  const value = watch(name);
  const id = useId();

  const [isCheckAll, setIsCheckAll] = useState(false);

  const handleCheckAll = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { checked } = event.target;
    setIsCheckAll(checked);
    setValue(name, checked ? _value : []);
    onChange(event);
  };

  useEffect(() => {
    if (!isSelectAll) return;
    const allChecked = _value.every((v: any) => {
      return value && value?.includes(v);
    });
    setIsCheckAll(allChecked);
  }, [value, _value]);

  return (
    <label className={clsx(labelClassStr ? labelClassStr : 'flex w-full items-center gap-[10px]')}>
      <input
        type="checkbox"
        name={name}
        ref={ref}
        id={id}
        className={classStr ?? 'check-box'}
        onChange={isSelectAll ? handleCheckAll : onChange}
        onFocus={onBlur}
        onBlur={onBlur}
        disabled={disabled}
        readOnly={readOnly}
        aria-invalid={errors[name] ? 'true' : 'false'}
        value={_value}
        checked={isSelectAll ? isCheckAll : undefined}
      />
      <span>동의체크박스</span>
      {label}
    </label>
  );
});
