import { useEffect, useRef, useState } from "react";
import { ActionDialog } from "../../shared/ActionDialog.jsx";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { PC_DATA_RESET_CONFIRMATION, resetPcApplicationData } from "./pc-data-reset.js";

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

  useEffect(() => {
    if (!open) {
      setPhase("confirm");
      setPending(false);
    }
    return () => clearTimeout(reloadTimer.current);
  }, [open]);

  async function confirmReset() {
    if (phase === "scheduled") {
      globalThis.location.reload();
      return;
    }
    setPending(true);
    try {
      await resetPcApplicationData(PC_DATA_RESET_CONFIRMATION);
      setPhase("scheduled");
      reloadTimer.current = setTimeout(() => globalThis.location.reload(), 2500);
    } catch (error) {
      setPhase(resetErrorPhase(error?.message));
    } finally {
      setPending(false);
    }
  }

  const scheduled = phase === "scheduled";
  const error = phase.startsWith("error-");
  return <ActionDialog
    open={open}
    title={t(scheduled ? "settings.resetPcScheduledTitle" : "settings.resetPcDataTitle")}
    description={t(scheduled ? "settings.resetPcScheduled" : "settings.resetPcDataDescription")}
    cancelLabel={scheduled ? "" : t("dialog.cancel")}
    confirmLabel={t(scheduled ? "settings.reconnectPc" : "settings.resetPcDataConfirm")}
    pendingLabel={t("settings.resettingPcData")}
    pending={pending}
    dismissDisabled={scheduled}
    tone="danger"
    onCancel={onClose}
    onConfirm={confirmReset}
  >
    {!scheduled && <div className="action-dialog-content">
      <strong>{t("settings.resetPcDeletesTitle")}</strong>
      <ul><li>{t("settings.resetPcDeletesSessions")}</li><li>{t("settings.resetPcDeletesPreferences")}</li><li>{t("settings.resetPcDeletesPairings")}</li><li>{t("settings.resetPcDeletesLogs")}</li></ul>
      <strong>{t("settings.resetPcKeepsTitle")}</strong>
      <ul><li>{t("settings.resetPcKeepsCodex")}</li><li>{t("settings.resetPcKeepsConfiguration")}</li><li>{t("settings.resetPcKeepsReceipts")}</li><li>{t("settings.resetPcKeepsAccounts")}</li></ul>
      {error && <p className="action-dialog-error" role="alert">{t(resetErrorMessage(phase))}</p>}
    </div>}
  </ActionDialog>;
}

function resetErrorPhase(code) {
  if (code === "application_data_in_use") return "error-in-use";
  if (code === "application_data_restart_unavailable") return "error-unmanaged";
  return "error-failed";
}

function resetErrorMessage(phase) {
  if (phase === "error-in-use") return "settings.resetPcInUse";
  if (phase === "error-unmanaged") return "settings.resetPcUnmanaged";
  return "settings.resetPcFailed";
}
