"use client";

import { useState } from "react";
import { getTOTPSetup, confirmTOTPSetup, disableTOTP } from "@/lib/api";

export function useTotpSettings() {
  const [totpEnabled, setTotpEnabled] = useState(false);
  const [showSetup, setShowSetup] = useState(false);
  const [qrCode, setQrCode] = useState("");
  const [secret, setSecret] = useState("");
  const [totpCode, setTotpCode] = useState("");
  const [totpError, setTotpError] = useState("");
  const [totpSuccess, setTotpSuccess] = useState("");
  const [totpLoading, setTotpLoading] = useState(false);
  const [disableDialogOpen, setDisableDialogOpen] = useState(false);
  const [disableCode, setDisableCode] = useState("");
  const [disableError, setDisableError] = useState("");
  const [disableLoading, setDisableLoading] = useState(false);

  async function handleSetupTOTP() {
    setTotpError("");
    setTotpSuccess("");
    setTotpLoading(true);
    try {
      const data = await getTOTPSetup();
      setQrCode(data.qr_code || "");
      setSecret(data.secret);
      setShowSetup(true);
      setTotpCode("");
    } catch (err) {
      setTotpError(err instanceof Error ? err.message : "TOTP-Setup fehlgeschlagen");
    } finally {
      setTotpLoading(false);
    }
  }

  async function handleConfirmTOTP(e: React.FormEvent) {
    e.preventDefault();
    setTotpError("");
    setTotpLoading(true);
    try {
      await confirmTOTPSetup(totpCode);
      setTotpEnabled(true);
      setShowSetup(false);
      setTotpSuccess("2FA wurde erfolgreich aktiviert.");
      setQrCode("");
      setSecret("");
      setTotpCode("");
    } catch (err) {
      setTotpError(err instanceof Error ? err.message : "Ungueltiger Code");
    } finally {
      setTotpLoading(false);
    }
  }

  async function handleDisableTOTP() {
    setDisableError("");
    setDisableLoading(true);
    try {
      await disableTOTP(disableCode);
      setTotpEnabled(false);
      setDisableDialogOpen(false);
      setDisableCode("");
      setTotpSuccess("2FA wurde deaktiviert.");
    } catch (err) {
      setDisableError(err instanceof Error ? err.message : "Ungueltiger Code");
    } finally {
      setDisableLoading(false);
    }
  }

  function cancelSetup() {
    setShowSetup(false);
    setQrCode("");
    setSecret("");
    setTotpCode("");
    setTotpError("");
  }

  function openDisableDialog() {
    setDisableDialogOpen(true);
    setDisableCode("");
    setDisableError("");
  }

  return {
    totpEnabled,
    showSetup,
    qrCode,
    secret,
    totpCode,
    setTotpCode,
    totpError,
    totpSuccess,
    totpLoading,
    disableDialogOpen,
    setDisableDialogOpen,
    disableCode,
    setDisableCode,
    disableError,
    disableLoading,
    handleSetupTOTP,
    handleConfirmTOTP,
    handleDisableTOTP,
    cancelSetup,
    openDisableDialog,
  };
}
