"use client";

import { useState, useCallback } from "react";
import { useTranslationStore } from "@/lib/store";
import { API_BASE } from "@/lib/config";
import { ADMIN_TIMEOUT_MS } from "./useAdminUsers";

export function useAdminResetPassword() {
  const [isResetting, setIsResetting] = useState(false);

  const resetPassword = useCallback(async (userId: string, newPassword: string) => {
    const token = useTranslationStore.getState().settings.adminToken;
    if (!token) {
      throw new Error("Session admin requise");
    }
    setIsResetting(true);
    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), ADMIN_TIMEOUT_MS);
      const res = await fetch(`${API_BASE}/api/v1/admin/users/${encodeURIComponent(userId)}/password`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ new_password: newPassword }),
        signal: controller.signal,
      });
      clearTimeout(timeoutId);
      if (!res.ok) {
        const j = await res.json().catch(() => ({}));
        const detail = j.detail;
        const msg =
          typeof detail === "string"
            ? detail
            : Array.isArray(detail)
              ? detail[0]?.msg
              : j.message;
        throw new Error(msg || `Erreur HTTP ${res.status}`);
      }
    } finally {
      setIsResetting(false);
    }
  }, []);

  return { resetPassword, isResetting };
}
