"use client";

import { useState } from "react";
import { changePassword } from "@/lib/api";

export function usePasswordChange() {
  const [currentPw, setCurrentPw] = useState("");
  const [newPw, setNewPw] = useState("");
  const [confirmPw, setConfirmPw] = useState("");
  const [pwError, setPwError] = useState("");
  const [pwSuccess, setPwSuccess] = useState("");
  const [pwLoading, setPwLoading] = useState(false);

  async function handleChangePassword(e: React.FormEvent) {
    e.preventDefault();
    setPwError("");
    setPwSuccess("");

    if (newPw.length < 8) {
      setPwError("Das neue Passwort muss mindestens 8 Zeichen lang sein.");
      return;
    }
    if (newPw !== confirmPw) {
      setPwError("Die Passwoerter stimmen nicht ueberein.");
      return;
    }

    setPwLoading(true);
    try {
      await changePassword(currentPw, newPw);
      setPwSuccess("Passwort wurde erfolgreich geaendert.");
      setCurrentPw("");
      setNewPw("");
      setConfirmPw("");
    } catch (err) {
      setPwError(err instanceof Error ? err.message : "Fehler beim Aendern des Passworts");
    } finally {
      setPwLoading(false);
    }
  }

  return {
    currentPw,
    setCurrentPw,
    newPw,
    setNewPw,
    confirmPw,
    setConfirmPw,
    pwError,
    pwSuccess,
    pwLoading,
    handleChangePassword,
  };
}
