"use client";

import { useState } from "react";
import { useAdminDashboard } from "../useAdminDashboard";
import { useCleanup } from "../useCleanup";
import { useTranslationStore } from "@/lib/store";
import { API_BASE } from "@/lib/config";

export function useSystemPage() {
  const { data, isLoading, error } = useAdminDashboard();
  const { isPurging, purgeResult, error: cleanupError, triggerCleanup } = useCleanup();
  const { settings } = useTranslationStore();

  const [isResetting, setIsResetting] = useState(false);
  const [resetResult, setResetResult] = useState<{ keys_deleted: number; message: string } | null>(null);

  const handleCleanup = () => triggerCleanup();

  const handleResetQuotas = async () => {
    if (!settings.adminToken) return;
    setIsResetting(true);
    setResetResult(null);
    try {
      const res = await fetch(`${API_BASE}/api/v1/admin/quota/reset`, {
        method: "POST",
        headers: { Authorization: `Bearer ${settings.adminToken}` },
      });
      const json = await res.json();
      setResetResult(json);
    } catch {
      setResetResult({ keys_deleted: 0, message: "Erreur réseau" });
    } finally {
      setIsResetting(false);
    }
  };

  return {
    data,
    isLoading,
    error: error || cleanupError,
    isPurging,
    purgeResult,
    handleCleanup,
    isResetting,
    resetResult,
    handleResetQuotas,
  };
}
