import { forwardRef } from "react";
import { useMergeEvents } from "@reins/hooks";

import { FormButtonProps } from "./form-button.types";
import { useActions } from "hooks/use-actions/use-actions";
import { FormAdapter } from "utils";

export const FormButton = forwardRef<
  HTMLButtonElement,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  FormButtonProps & { useFormContext: (componentName: string) => { form: FormAdapter<any, any> } }
>(({ useFormContext, type = "button", onClick, disabled, loading, ...rest }, ref) => {
  const { form } = useFormContext("FormButton");
  const { goBack } = useActions(form);

  const [{ isSubmitting, isValidating }] = form.store.useStore();

  const isDisabled = disabled || isValidating || isSubmitting;
  const isLoading = loading || (type === "submit" && isSubmitting);

  const buttonType = type === "back" ? "button" : type;

  const handleClick = useMergeEvents(onClick, () => {
    if (type === "back") goBack();
  });

  return (
    <button
      {...rest}
      ref={ref}
      // eslint-disable-next-line react/button-has-type
      type={buttonType}
      onClick={handleClick}
      disabled={isDisabled}
      aria-busy={isLoading}
    />
  );
});
