import React, {
  ComponentPropsWithRef,
  forwardRef,
  ReactNode,
  useEffect,
  useRef,
} from "react";
import { useMergeRefs } from "use-callback-ref";

import { Typography } from "../typography/Typography";
import { twMerge } from "../../../tailwind.config";
import { CheckboxIcon } from "./CheckboxIcon";

export interface CheckboxProps
  extends Omit<ComponentPropsWithRef<"input">, "className"> {
  indeterminate?: boolean;
  label?: ReactNode;
  ESCAPE_className?: string;
}

export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
  ({ label, indeterminate = false, ESCAPE_className, ...restProps }, ref) => {
    const innerRef = useRef<HTMLInputElement>(null);
    const mergedRef = useMergeRefs([ref, innerRef]);

    useEffect(() => {
      innerRef.current && (innerRef.current.indeterminate = indeterminate);
    }, [innerRef, indeterminate]);

    return (
      <label
        className={twMerge(
          "flex cursor-pointer items-center gap-x-4",
          ESCAPE_className
        )}
      >
        <input
          type="checkbox"
          ref={mergedRef}
          {...restProps}
          className="peer sr-only"
        />

        <CheckboxIcon indeterminate={indeterminate} />
        <Typography size="200">{label}</Typography>
      </label>
    );
  }
);
