"use client";

import { useState, useCallback } from "react";
import { getServices, serviceAction, type ServiceStatus } from "@/lib/api";

export function useAdminServices() {
  const [services, setServices] = useState<ServiceStatus[]>([]);
  const [servicesLoading, setServicesLoading] = useState(false);
  const [serviceActionLoading, setServiceActionLoading] = useState<string | null>(null);
  const [serviceError, setServiceError] = useState("");

  const loadServices = useCallback(async () => {
    setServicesLoading(true);
    setServiceError("");
    try {
      const data = await getServices();
      setServices(data || []);
    } catch {
      setServiceError("Dienste konnten nicht abgerufen werden.");
    } finally {
      setServicesLoading(false);
    }
  }, []);

  async function handleServiceAction(name: string, action: "start" | "stop" | "restart" | "enable" | "disable" | "block_external" | "allow_external") {
    setServiceActionLoading(`${name}:${action}`);
    setServiceError("");
    try {
      const updated = await serviceAction(name, action);
      setServices((prev) => prev.map((s) => (s.name === updated.name ? updated : s)));
    } catch (e: unknown) {
      setServiceError(e instanceof Error ? e.message : "Aktion fehlgeschlagen.");
    } finally {
      setServiceActionLoading(null);
    }
  }

  return {
    services,
    servicesLoading,
    serviceActionLoading,
    serviceError,
    loadServices,
    handleServiceAction,
  };
}
