import type { ReactNode } from "react";
import { Controller, useFormContext } from "react-hook-form";

import createUseStyles from "../../theme/createUseStyles";
import { cn } from "../../util/cn";
import { Checkmark } from "@carbon/icons-react";

const useStyles = createUseStyles<{ isChecked?: boolean }>({
  buttonDisabled: {
    backgroundColor: ({ isChecked }) => isChecked === true && "var(--color-darkGrey)",
  },
  buttonError: {
    border: "2px solid var(--color-red) !important",
  },
});

export default function CheckboxInput({
  children,
  className,
  name,
  label,
  error = false,
}: React.PropsWithChildren<{
  className?: string;
  error?: boolean;
  label?: string | ReactNode;
  name: string;
}>) {
  const { control, watch } = useFormContext();
  const isChecked = watch(name) as boolean;
  const classes = useStyles({ isChecked });

  return (
    <Controller
      name={name}
      control={control}
      render={(props) => {
        const {
          field: { onChange, ...field },
        } = props;
        return (
          <div className={cn("flex", className)}>
            <input
              className="hidden absolute"
              data-testid={`checkbox-input-${name}`}
              type="text"
              aria-hidden
              readOnly
              {...field}
            />
            {/** biome-ignore lint/a11y/useSemanticElements: <explanation> todo*/}
            <div
              className={cn("items-center bg-black border-white cursor-pointer flex justify-center w-l h-l min-w-l min-h-l outline-none", {
                [classes.buttonError]: error,
                [cn("border-white cursor-default", classes.buttonDisabled)]: field.disabled,
              })}
              onClick={() => {
                // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
                onChange(!field.value);
              }}
              onKeyUp={() => {
                // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
                onChange(!field.value);
              }}
              data-testid={`checkbox-${name}`}
              role="button"
              tabIndex={0}
            >
              {isChecked ? <Checkmark /> : null}
            </div>
            <span className="word-break-break-word user-select-none pl-m font-lineHeight-l font-size-s text-white max-w-full">
              {[null, undefined].includes(label as null)
                ? null
                : label}
              {children}
            </span>
          </div>
        );
      }}
    />
  );
}
