{
  config,
  lib,
  ...
}:
with lib; let
  cfg = config.homelab.services.monitoring-stack;
in {
  imports = [
    ./prometheus.nix
    ./alertmanager.nix
    ./grafana.nix
  ];

  options.homelab.services.monitoring-stack = {
    enable = mkEnableOption "Complete monitoring stack (Prometheus + Alertmanager + Grafana)";

    prometheus = {
      enable = mkOption {
        type = types.bool;
        default = true;
        description = "Enable Prometheus";
      };
    };

    alertmanager = {
      enable = mkOption {
        type = types.bool;
        default = true;
        description = "Enable Alertmanager";
      };
    };

    grafana = {
      enable = mkOption {
        type = types.bool;
        default = true;
        description = "Enable Grafana";
      };
    };
  };

  config = mkIf cfg.enable {
    # Enable services based on configuration
    homelab.services.prometheus.enable = mkDefault cfg.prometheus.enable;
    homelab.services.alertmanager.enable = mkDefault cfg.alertmanager.enable;
    homelab.services.grafana.enable = mkDefault cfg.grafana.enable;

    # Configure Prometheus to use Alertmanager if both are enabled
    homelab.services.prometheus.alertmanager = mkIf (cfg.prometheus.enable && cfg.alertmanager.enable) {
      enable = true;
      url = "http://localhost:${toString config.homelab.services.alertmanager.port}";
    };

    # Configure Grafana to use Prometheus if both are enabled
    homelab.services.grafana.datasources.prometheus = mkIf (cfg.prometheus.enable && cfg.grafana.enable) {
      url = "http://localhost:${toString config.homelab.services.prometheus.port}";
    };
  };
}
