"use client";

import { DEFAULT_ADMIN_EMAIL } from "@shared";
import { AlertTriangle } from "lucide-react";
import Link from "next/link";
import { DefaultCredentialsWarning } from "@/components/default-credentials-warning";
import {
  useDefaultCredentialsEnabled,
  useHasPermissions,
  useSession,
} from "@/lib/auth/auth.query";
import { useDisableBasicAuth, useFeature } from "@/lib/config/config.query";

export function SidebarWarnings() {
  const { data: session } = useSession();
  const userEmail = session?.user?.email;
  const { data: defaultCredentialsEnabled, isLoading: isLoadingCreds } =
    useDefaultCredentialsEnabled();
  const globalToolPolicy = useFeature("globalToolPolicy");
  const disableBasicAuth = useDisableBasicAuth();
  const { data: canUpdateOrg } = useHasPermissions({
    organization: ["update"],
  });
  const { data: canUpdateAgentSettings } = useHasPermissions({
    agentSettings: ["update"],
  });

  const isPermissive = globalToolPolicy === "permissive";

  // Security-engine fixes live under Agent Settings; default-credential fixes remain org-scoped.
  const showSecurityEngineWarning =
    !!session && canUpdateAgentSettings === true && isPermissive;
  const showDefaultCredsWarning =
    canUpdateOrg === true &&
    disableBasicAuth === false &&
    !isLoadingCreds &&
    defaultCredentialsEnabled !== undefined &&
    defaultCredentialsEnabled &&
    userEmail === DEFAULT_ADMIN_EMAIL;

  // Don't render anything if no warnings
  if (!showSecurityEngineWarning && !showDefaultCredsWarning) {
    return null;
  }

  return (
    <div className="px-2 pb-1 space-y-1">
      {showSecurityEngineWarning && (
        <div className="rounded-lg border bg-card px-3 py-1.5 text-xs text-destructive">
          <p className="flex items-center gap-1.5 whitespace-nowrap">
            <AlertTriangle className="h-3.5 w-3.5 shrink-0" />
            <span>
              Security engine off
              {" - "}
              <Link
                href="/mcp/tool-guardrails"
                className="underline font-medium"
              >
                Fix
              </Link>
            </span>
          </p>
        </div>
      )}
      {showDefaultCredsWarning && <DefaultCredentialsWarning alwaysShow slim />}
    </div>
  );
}
