"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import NavigationButton, {
  type NavigationButtonProps,
} from "./navigation-button";
import { localizePath } from "@/translations/config";
import { useI18n } from "@/translations/provider";
import { useQuestionAnswers } from "./question-answer-storage";
import { markFirstEntryCompleted } from "@/lib/first-entry-helper";

export type QuestionExitNavigationButtonProps = NavigationButtonProps & {
  exitHref?: string;
};

export function QuestionExitNavigationButton({
  exitHref,
  ...props
}: QuestionExitNavigationButtonProps) {
  const router = useRouter();
  const { locale } = useI18n();
  const { flushAnswers } = useQuestionAnswers();

  const [isNavigating, setIsNavigating] = useState(false);

  return (
    <NavigationButton
      {...props}
      disabled={props.disabled || isNavigating}
      onClick={async (event) => {
        props.onClick?.(event);

        if (event.defaultPrevented || isNavigating) {
          return;
        }

        event.preventDefault();
        setIsNavigating(true);

        try {
          markFirstEntryCompleted();
          await flushAnswers({ force: true });
        } catch {
          // ignore
        } finally {
          const target = localizePath(exitHref || "/questions-list", locale);
          router.push(target);
        }
      }}
    />
  );
}

export default QuestionExitNavigationButton;
