import { ButtonHTMLAttributes, useRef } from "preact/compat";
import { useCallback, useEffect, useState } from "preact/hooks";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";

interface SubmitButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  buttonLabel?: string;
  isLastQuestion: boolean;
  focus?: boolean;
}

export function SubmitButton({
  buttonLabel,
  isLastQuestion,
  tabIndex = 1,
  focus = false,
  onClick,
  disabled,
  type,
  ...props
}: SubmitButtonProps) {
  const buttonRef = useRef<HTMLButtonElement>(null);
  const [isProcessing, setIsProcessing] = useState(false);

  // throttle the button submit to prevent multiple submissions
  // works by setting a timeout to reset the isProcessing state
  // TODO: Refactor
  useEffect(() => {
    if (isProcessing) {
      const timer = setTimeout(() => {
        setIsProcessing(false);
      }, 300);

      return () => {
        clearTimeout(timer);
      };
    }
  }, [isProcessing]);
  const { t } = useTranslation();

  const handleKeyDown = useCallback(
    (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && !disabled && !isProcessing) {
        event.preventDefault();
        setIsProcessing(true);
        const button = buttonRef.current;
        if (button) {
          button.click();
        }
      }
    },
    [disabled, isProcessing]
  );

  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [handleKeyDown]);

  useEffect(() => {
    if (buttonRef.current && focus) {
      setTimeout(() => {
        buttonRef.current?.focus();
      }, 200);
    }
  }, [focus]);

  return (
    <button
      {...props}
      dir="auto"
      ref={buttonRef}
      type={type}
      tabIndex={tabIndex}
      autoFocus={focus}
      className={cn(
        "border-submit-button-border focus:ring-focus mb-1 flex items-center justify-center border leading-4 shadow-xs focus:ring-2 focus:ring-offset-2 focus:outline-hidden enabled:hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60",
        "button-custom"
      )}
      style={{
        borderRadius: "var(--fb-button-border-radius)",
        backgroundColor: "var(--fb-button-bg-color)",
        color: "var(--fb-button-text-color)",
        height: "var(--fb-button-height)",
        fontSize: "var(--fb-button-font-size)",
        fontWeight: "var(--fb-button-font-weight)",
        paddingLeft: "var(--fb-button-padding-x)",
        paddingRight: "var(--fb-button-padding-x)",
        paddingTop: "var(--fb-button-padding-y)",
        paddingBottom: "var(--fb-button-padding-y)",
      }}
      onClick={onClick}
      disabled={disabled}>
      {buttonLabel || (isLastQuestion ? t("common.finish") : t("common.next"))}
    </button>
  );
}
