"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Loader2, Save, Shield, Trash2, ShieldCheck } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Button } from "@open-mercato/ui/primitives/button";
import { Checkbox } from "@open-mercato/ui/primitives/checkbox";
import { Label } from "@open-mercato/ui/primitives/label";
import { apiCall, apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
async function fetchSettings() {
  const { result, status } = await apiCallOrThrow(
    "/api/ai_assistant/settings",
    { method: "GET", credentials: "include" },
    { errorMessage: "Failed to load AI settings" }
  );
  if (!result) throw new Error(`Failed to load settings (${status})`);
  return result;
}
function snapshotToEditState(snapshot) {
  return {
    allowedProviders: snapshot?.allowedProviders ?? null,
    allowedModelsByProvider: { ...snapshot?.allowedModelsByProvider ?? {} }
  };
}
function AiTenantAllowlistPageClient() {
  const t = useT();
  const queryClient = useQueryClient();
  const settingsQuery = useQuery({ queryKey: ["ai_assistant", "settings"], queryFn: fetchSettings, staleTime: 0 });
  const [editState, setEditState] = React.useState({
    allowedProviders: null,
    allowedModelsByProvider: {}
  });
  const [dirty, setDirty] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [clearing, setClearing] = React.useState(false);
  const [feedback, setFeedback] = React.useState(null);
  const { runMutation: runSaveAllowlistMutation } = useGuardedMutation({
    contextId: "ai-tenant-allowlist-save"
  });
  const { runMutation: runClearAllowlistMutation } = useGuardedMutation({
    contextId: "ai-tenant-allowlist-clear"
  });
  React.useEffect(() => {
    if (settingsQuery.data) {
      setEditState(snapshotToEditState(settingsQuery.data.tenantAllowlist));
      setDirty(false);
    }
  }, [settingsQuery.data]);
  const pageHeader = /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
    /* @__PURE__ */ jsxs("h1", { className: "flex items-center gap-2 text-2xl font-bold", children: [
      /* @__PURE__ */ jsx(Shield, { className: "size-6" }),
      t("ai_assistant.allowlist.title", "AI provider & model allowlist")
    ] }),
    /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: t(
      "ai_assistant.allowlist.subtitle",
      "Limit which providers and models the runtime, settings, and chat picker may use for this tenant. The env allowlist is the outer constraint \u2014 tenant picks narrow it further."
    ) })
  ] });
  if (settingsQuery.isLoading) {
    return /* @__PURE__ */ jsxs("div", { className: "flex max-w-3xl flex-col gap-4", children: [
      pageHeader,
      /* @__PURE__ */ jsxs("div", { className: "flex w-fit items-center gap-2 rounded-md border border-border bg-card px-3 py-2 text-sm text-muted-foreground", role: "status", children: [
        /* @__PURE__ */ jsx(Loader2, { className: "size-4 animate-spin" }),
        t("ai_assistant.allowlist.loading", "Loading allowlist\u2026")
      ] })
    ] });
  }
  if (settingsQuery.isError || !settingsQuery.data) {
    return /* @__PURE__ */ jsxs("div", { className: "flex max-w-3xl flex-col gap-4", children: [
      pageHeader,
      /* @__PURE__ */ jsxs(Alert, { variant: "destructive", children: [
        /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.allowlist.loadError.title", "Failed to load allowlist") }),
        /* @__PURE__ */ jsx(AlertDescription, { children: settingsQuery.error instanceof Error ? settingsQuery.error.message : t("ai_assistant.allowlist.loadError.body", "Try refreshing the page.") })
      ] })
    ] });
  }
  const settings = settingsQuery.data;
  const envAllowedProviders = settings.allowlist.providers;
  const envModelsByProvider = settings.allowlist.modelsByProvider;
  const editableProviders = settings.allowlistProviders ?? settings.availableProviders;
  const candidateProviders = editableProviders.filter((p) => {
    if (envAllowedProviders === null) return true;
    return envAllowedProviders.some((id) => id.toLowerCase() === p.id.toLowerCase());
  });
  const tenantPickedProviders = editState.allowedProviders;
  const isProviderEnabled = (id) => {
    if (tenantPickedProviders === null) return true;
    return tenantPickedProviders.includes(id);
  };
  const toggleProvider = (id, next) => {
    setDirty(true);
    setFeedback(null);
    setEditState((prev) => {
      const current = prev.allowedProviders;
      if (next) {
        const list2 = current === null ? [id] : Array.from(/* @__PURE__ */ new Set([...current, id]));
        return { ...prev, allowedProviders: list2 };
      }
      const list = current === null ? candidateProviders.map((p) => p.id).filter((pid) => pid !== id) : current.filter((pid) => pid !== id);
      return { ...prev, allowedProviders: list };
    });
  };
  const isModelEnabled = (providerId, modelId) => {
    const list = editState.allowedModelsByProvider[providerId];
    if (list === void 0) return true;
    return list.includes(modelId);
  };
  const toggleModel = (providerId, modelId, next) => {
    setDirty(true);
    setFeedback(null);
    const provider = candidateProviders.find((p) => p.id === providerId);
    const allModelIds = provider?.defaultModels.map((m) => m.id) ?? [];
    setEditState((prev) => {
      const current = prev.allowedModelsByProvider[providerId];
      const allowedModelsByProvider = { ...prev.allowedModelsByProvider };
      if (next) {
        const list = current === void 0 ? [modelId] : Array.from(/* @__PURE__ */ new Set([...current, modelId]));
        allowedModelsByProvider[providerId] = list;
      } else {
        const baseline = current === void 0 ? allModelIds : current;
        const list = baseline.filter((id) => id !== modelId);
        allowedModelsByProvider[providerId] = list;
      }
      return { ...prev, allowedModelsByProvider };
    });
  };
  const resetTenantPicks = () => {
    setDirty(true);
    setFeedback(null);
    setEditState({ allowedProviders: null, allowedModelsByProvider: {} });
  };
  const handleSave = async () => {
    setSaving(true);
    setFeedback(null);
    try {
      await runSaveAllowlistMutation({
        operation: async () => {
          const { ok, status, result } = await apiCall(
            "/api/ai_assistant/settings/allowlist",
            {
              method: "PUT",
              credentials: "include",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                allowedProviders: editState.allowedProviders,
                allowedModelsByProvider: editState.allowedModelsByProvider
              })
            }
          );
          if (!ok) {
            throw new Error(
              result?.error ?? t("ai_assistant.allowlist.save.error", `Save failed (${status})`)
            );
          }
        },
        context: {}
      });
      const successText = t("ai_assistant.allowlist.save.success", "Allowlist saved.");
      setFeedback({ kind: "ok", text: successText });
      flash(successText, "success");
      setDirty(false);
      await queryClient.invalidateQueries({ queryKey: ["ai_assistant", "settings"] });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setFeedback({ kind: "error", text: message });
      flash(message, "error");
    } finally {
      setSaving(false);
    }
  };
  const handleClear = async () => {
    setClearing(true);
    setFeedback(null);
    try {
      await runClearAllowlistMutation({
        operation: async () => {
          const { ok, status, result } = await apiCall(
            "/api/ai_assistant/settings/allowlist",
            { method: "DELETE", credentials: "include" }
          );
          if (!ok) {
            throw new Error(
              result?.error ?? t("ai_assistant.allowlist.clear.error", `Clear failed (${status})`)
            );
          }
        },
        context: {}
      });
      const successText = t(
        "ai_assistant.allowlist.clear.success",
        "Tenant allowlist cleared. Env-only enforcement applies."
      );
      setFeedback({ kind: "ok", text: successText });
      flash(successText, "success");
      setDirty(false);
      await queryClient.invalidateQueries({ queryKey: ["ai_assistant", "settings"] });
    } catch (err) {
      const message = err instanceof Error ? err.message : String(err);
      setFeedback({ kind: "error", text: message });
      flash(message, "error");
    } finally {
      setClearing(false);
    }
  };
  const envBanner = envAllowedProviders === null && Object.keys(envModelsByProvider).length === 0 ? null : /* @__PURE__ */ jsxs(Alert, { children: [
    /* @__PURE__ */ jsx(AlertTitle, { children: t("ai_assistant.allowlist.envBanner.title", "Env allowlist is in effect") }),
    /* @__PURE__ */ jsxs(AlertDescription, { className: "space-y-1", children: [
      envAllowedProviders ? /* @__PURE__ */ jsxs("div", { children: [
        t("ai_assistant.allowlist.envBanner.providers", "OM_AI_AVAILABLE_PROVIDERS"),
        ": ",
        /* @__PURE__ */ jsx("code", { className: "font-mono text-xs", children: envAllowedProviders.join(", ") })
      ] }) : null,
      Object.keys(envModelsByProvider).map((pid) => /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsxs("code", { className: "font-mono text-xs", children: [
          "OM_AI_AVAILABLE_MODELS_",
          pid.toUpperCase()
        ] }),
        ": ",
        envModelsByProvider[pid].join(", ")
      ] }, pid)),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: t("ai_assistant.allowlist.envBanner.note", "Tenant picks may not widen the env list \u2014 values outside it are hidden.") })
    ] })
  ] });
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-6 max-w-3xl", children: [
    pageHeader,
    envBanner,
    feedback ? /* @__PURE__ */ jsx(Alert, { variant: feedback.kind === "error" ? "destructive" : void 0, children: /* @__PURE__ */ jsx(AlertDescription, { children: feedback.text }) }) : null,
    /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-6 space-y-6", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("ai_assistant.allowlist.providers.title", "Providers") }),
          /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
            "ai_assistant.allowlist.providers.help",
            "Untick to forbid the runtime from using a provider for this tenant. Tick all to inherit the env allowlist."
          ) })
        ] }),
        /* @__PURE__ */ jsx(
          "span",
          {
            className: settings.effectiveAllowlist.tenantOverridesActive ? "inline-flex size-8 items-center justify-center rounded-md text-status-success-icon" : "inline-flex size-8 items-center justify-center rounded-md text-status-warning-icon",
            role: "img",
            "aria-label": settings.effectiveAllowlist.tenantOverridesActive ? t("ai_assistant.allowlist.badge.active", "Tenant rules active") : t("ai_assistant.allowlist.badge.envOnly", "Env-only"),
            title: settings.effectiveAllowlist.tenantOverridesActive ? t("ai_assistant.allowlist.badge.active", "Tenant rules active") : t("ai_assistant.allowlist.badge.envOnly", "Env-only"),
            children: settings.effectiveAllowlist.tenantOverridesActive ? /* @__PURE__ */ jsx(ShieldCheck, { className: "size-5", "aria-hidden": true }) : /* @__PURE__ */ jsx(Shield, { className: "size-5", "aria-hidden": true })
          }
        )
      ] }),
      candidateProviders.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("ai_assistant.allowlist.providers.empty", "No configured providers within the env allowlist.") }) : /* @__PURE__ */ jsx("div", { className: "space-y-4", children: candidateProviders.map((provider) => {
        const enabled = isProviderEnabled(provider.id);
        const envModels = envModelsByProvider[provider.id];
        const candidateModels = envModels ? provider.defaultModels.filter((m) => envModels.includes(m.id)) : provider.defaultModels;
        return /* @__PURE__ */ jsxs("div", { className: "rounded-md border p-4 space-y-3", children: [
          /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between gap-3", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
            /* @__PURE__ */ jsx(
              Checkbox,
              {
                id: `provider-${provider.id}`,
                checked: enabled,
                onCheckedChange: (value) => toggleProvider(provider.id, value === true)
              }
            ),
            /* @__PURE__ */ jsx(Label, { htmlFor: `provider-${provider.id}`, className: "font-medium", children: provider.name }),
            provider.configured ? /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: t("ai_assistant.allowlist.providers.configured", "configured") }) : /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs text-muted-foreground", children: t("ai_assistant.allowlist.providers.notConfigured", "not configured") })
          ] }) }),
          enabled && candidateModels.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "ml-7 space-y-2", children: [
            /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: t("ai_assistant.allowlist.models.help", "Tick the models tenants may pick. Empty = no model restriction (inherit env).") }),
            /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-2", children: candidateModels.map((model) => {
              const checked = isModelEnabled(provider.id, model.id);
              return /* @__PURE__ */ jsxs(
                "label",
                {
                  className: "flex items-center gap-2 text-sm",
                  children: [
                    /* @__PURE__ */ jsx(
                      Checkbox,
                      {
                        checked,
                        onCheckedChange: (value) => toggleModel(provider.id, model.id, value === true)
                      }
                    ),
                    /* @__PURE__ */ jsx("span", { className: "font-mono text-xs", children: model.id }),
                    model.id === provider.defaultModel ? /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: t("ai_assistant.allowlist.models.default", "default") }) : null
                  ]
                },
                `${provider.id}-${model.id}`
              );
            }) })
          ] }) : null
        ] }, provider.id);
      }) })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
      /* @__PURE__ */ jsxs(Button, { onClick: () => void handleSave(), disabled: !dirty || saving, className: "gap-2", children: [
        saving ? /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(Save, { className: "h-4 w-4" }),
        t("ai_assistant.allowlist.actions.save", "Save allowlist")
      ] }),
      /* @__PURE__ */ jsx(
        Button,
        {
          variant: "outline",
          onClick: resetTenantPicks,
          disabled: saving || clearing,
          className: "gap-2",
          children: t("ai_assistant.allowlist.actions.reset", "Reset to env defaults")
        }
      ),
      /* @__PURE__ */ jsxs(
        Button,
        {
          variant: "ghost",
          onClick: () => void handleClear(),
          disabled: clearing || saving || !settings.tenantAllowlist,
          className: "gap-2",
          children: [
            clearing ? /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" }),
            t("ai_assistant.allowlist.actions.clearStored", "Clear stored allowlist")
          ]
        }
      )
    ] })
  ] });
}
var AiTenantAllowlistPageClient_default = AiTenantAllowlistPageClient;
export {
  AiTenantAllowlistPageClient,
  AiTenantAllowlistPageClient_default as default
};
//# sourceMappingURL=AiTenantAllowlistPageClient.js.map
