import { useEffect, useState } from "react";
import { useI18n } from "./I18nProvider.jsx";
import { ActionDialog } from "./ActionDialog.jsx";

export function ResetCreditDialog({ open, accountName, onClose, onUse }) {
  const { t } = useI18n();
  const [phase, setPhase] = useState("confirm");
  const [pending, setPending] = useState(false);

  useEffect(() => {
    if (!open) {
      setPhase("confirm");
      setPending(false);
    }
  }, [open, accountName]);

  async function confirmUse() {
    if (phase !== "confirm") {
      onClose();
      return;
    }
    setPending(true);
    try {
      const result = await onUse();
      if (result?.outcome === "nothingToReset") setPhase("nothing");
      else if (result?.outcome === "noCredit") setPhase("noCredit");
      else setPhase("success");
    } catch {
      setPhase("failed");
    } finally {
      setPending(false);
    }
  }

  const result = phase !== "confirm";
  return <ActionDialog
    open={open}
    title={t(result ? resetResultTitle(phase) : "context.resetDialogTitle")}
    description={t(result ? resetResultDescription(phase) : "context.resetConfirm", { name: accountName })}
    cancelLabel={result ? "" : t("dialog.cancel")}
    confirmLabel={result ? t("dialog.close") : t("context.useOneResetCredit")}
    pendingLabel={t("context.using")}
    pending={pending}
    onCancel={onClose}
    onConfirm={confirmUse}
  />;
}

function resetResultTitle(phase) {
  return phase === "success" ? "context.resetCompleteTitle" : "context.resetUnavailableTitle";
}

function resetResultDescription(phase) {
  if (phase === "success") return "context.resetComplete";
  if (phase === "nothing") return "context.noUsageReset";
  if (phase === "noCredit") return "context.noResetCredit";
  return "context.resetFailed";
}
