"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Card, CardHeader, CardTitle, CardContent } from "@open-mercato/ui/primitives/card";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { Button } from "@open-mercato/ui/primitives/button";
import { Switch } from "@open-mercato/ui/primitives/switch";
import { Input } from "@open-mercato/ui/primitives/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { LoadingMessage, ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
const UNSUPPORTED_CREDENTIAL_FIELD_TYPES = /* @__PURE__ */ new Set(["oauth", "ssh_keypair"]);
function isEditableCredentialField(field) {
  return !UNSUPPORTED_CREDENTIAL_FIELD_TYPES.has(field.type);
}
function resolveRouteId(value) {
  if (Array.isArray(value)) return value[0];
  return value;
}
function resolvePathnameId(pathname) {
  const parts = pathname.split("/").filter(Boolean);
  const bundleId = parts.at(-1);
  if (!bundleId || bundleId === "bundle" || bundleId === "integrations") return void 0;
  return decodeURIComponent(bundleId);
}
function BundleConfigPage({ params }) {
  const pathname = usePathname();
  const bundleId = resolveRouteId(params?.id) ?? resolvePathnameId(pathname);
  const t = useT();
  const [detail, setDetail] = React.useState(null);
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [credValues, setCredValues] = React.useState({});
  const [credentialsUpdatedAt, setCredentialsUpdatedAt] = React.useState(null);
  const [isSavingCreds, setIsSavingCreds] = React.useState(false);
  const [togglingIds, setTogglingIds] = React.useState(/* @__PURE__ */ new Set());
  const mutationContextId = React.useMemo(
    () => `integrations.bundle:${bundleId ?? "unknown"}`,
    [bundleId]
  );
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: mutationContextId
  });
  const resolveCurrentBundleId = React.useCallback(() => {
    return bundleId ?? (typeof window !== "undefined" ? resolvePathnameId(window.location.pathname) : void 0);
  }, [bundleId]);
  const load = React.useCallback(async () => {
    const currentBundleId = resolveCurrentBundleId();
    if (!currentBundleId) {
      setError(t("integrations.detail.loadError"));
      setIsLoading(false);
      return;
    }
    setIsLoading(true);
    setError(null);
    setIsNotFound(false);
    const call = await apiCall(
      `/api/integrations/${encodeURIComponent(currentBundleId)}`,
      void 0,
      { fallback: null }
    );
    if (!call.ok || !call.result) {
      if (call.status === 404) {
        setIsNotFound(true);
      } else {
        setError(t("integrations.detail.loadError"));
      }
      setIsLoading(false);
      return;
    }
    setDetail(call.result);
    const credCall = await apiCall(
      `/api/integrations/${encodeURIComponent(currentBundleId)}/credentials`,
      void 0,
      { fallback: null }
    );
    if (credCall.ok && credCall.result) {
      setCredentialsUpdatedAt(credCall.result.updatedAt ?? null);
    }
    if (credCall.ok && credCall.result?.credentials) {
      const next = { ...credCall.result.credentials };
      if (currentBundleId === "storage_s3") {
        const authMode = next.authMode;
        if (authMode !== "access_keys" && authMode !== "ambient") {
          const hasKeys = Boolean(next.accessKeyId || next.secretAccessKey);
          next.authMode = hasKeys ? "access_keys" : "ambient";
        }
      }
      setCredValues(next);
    }
    setIsLoading(false);
  }, [resolveCurrentBundleId, t]);
  React.useEffect(() => {
    void load();
  }, [load]);
  const handleSaveCredentials = React.useCallback(async () => {
    const currentBundleId = resolveCurrentBundleId();
    if (!currentBundleId) return;
    setIsSavingCreds(true);
    try {
      const call = await runMutation({
        mutationPayload: { bundleId: currentBundleId, credentials: credValues },
        context: {
          formId: mutationContextId,
          operation: "update",
          actionId: "save-credentials",
          resourceKind: "integrations.bundle",
          resourceId: currentBundleId,
          bundleId: currentBundleId,
          retryLastMutation
        },
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(credentialsUpdatedAt),
          () => apiCall(`/api/integrations/${encodeURIComponent(currentBundleId)}/credentials`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ credentials: credValues })
          }, { fallback: null })
        )
      });
      if (call.ok) {
        flash(t("integrations.detail.credentials.saved"), "success");
        await load();
      } else {
        flash(t("integrations.detail.credentials.saveError"), "error");
      }
    } catch {
      flash(t("integrations.detail.credentials.saveError"), "error");
    } finally {
      setIsSavingCreds(false);
    }
  }, [resolveCurrentBundleId, runMutation, mutationContextId, retryLastMutation, credValues, credentialsUpdatedAt, load, t]);
  const handleToggle = React.useCallback(async (integrationId, enabled, updatedAt) => {
    setTogglingIds((prev) => new Set(prev).add(integrationId));
    try {
      const call = await runMutation({
        mutationPayload: { integrationId, isEnabled: enabled },
        context: {
          formId: mutationContextId,
          operation: "update",
          actionId: "toggle-state",
          resourceKind: "integrations.integration",
          resourceId: integrationId,
          integrationId,
          retryLastMutation
        },
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(updatedAt),
          () => apiCall(`/api/integrations/${encodeURIComponent(integrationId)}/state`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ isEnabled: enabled })
          }, { fallback: null })
        )
      });
      if (call.ok) {
        const nextUpdatedAt = call.result?.updatedAt ?? null;
        setDetail((prev) => {
          if (!prev) return prev;
          return {
            ...prev,
            bundleIntegrations: prev.bundleIntegrations.map(
              (item) => item.id === integrationId ? { ...item, isEnabled: enabled, state: { updatedAt: nextUpdatedAt ?? item.state?.updatedAt ?? null } } : item
            )
          };
        });
      } else {
        flash(t("integrations.detail.stateError"), "error");
      }
    } catch {
      flash(t("integrations.detail.stateError"), "error");
    } finally {
      setTogglingIds((prev) => {
        const next = new Set(prev);
        next.delete(integrationId);
        return next;
      });
    }
  }, [runMutation, mutationContextId, retryLastMutation, t]);
  const handleBulkToggle = React.useCallback(async (enabled) => {
    if (!detail) return;
    const targets = detail.bundleIntegrations.filter((item) => item.isEnabled !== enabled);
    await Promise.all(targets.map((item) => handleToggle(item.id, enabled, item.state?.updatedAt)));
  }, [detail, handleToggle]);
  if (isLoading) return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("integrations.bundle.title") }) }) });
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("integrations.detail.notFound", "Integration not found."),
        backHref: "/backend/integrations",
        backLabel: t("integrations.detail.backToList", "Back to integrations")
      }
    ) }) });
  }
  if (error || !detail?.bundle) return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error ?? t("integrations.detail.loadError") }) }) });
  const credFields = (detail.bundle.credentials?.fields ?? []).filter(isEditableCredentialField);
  function isFieldVisible(field) {
    if (!field.visibleWhen) return true;
    return credValues[field.visibleWhen.field] === field.visibleWhen.equals;
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { className: "space-y-6", children: [
    /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Link, { href: "/backend/integrations", className: "text-sm text-muted-foreground hover:underline", children: t("integrations.detail.back") }) }),
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold", children: detail.bundle.title }),
      detail.bundle.description && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground mt-1", children: detail.bundle.description })
    ] }),
    credFields.length > 0 && /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: t("integrations.bundle.sharedCredentials") }) }),
      /* @__PURE__ */ jsxs(CardContent, { className: "space-y-4", children: [
        credFields.filter(isFieldVisible).map((field) => /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
          /* @__PURE__ */ jsxs("label", { className: "text-sm font-medium", children: [
            field.label,
            field.required && /* @__PURE__ */ jsx("span", { className: "text-red-500 ml-0.5", children: "*" })
          ] }),
          field.type === "select" && field.options ? /* @__PURE__ */ jsxs(
            Select,
            {
              value: credValues[field.key] || void 0,
              onValueChange: (value) => setCredValues((prev) => ({ ...prev, [field.key]: value ?? "" })),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "\u2014" }) }),
                /* @__PURE__ */ jsx(SelectContent, { children: field.options.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: opt.value, children: opt.label }, opt.value)) })
              ]
            }
          ) : field.type === "boolean" ? /* @__PURE__ */ jsx(
            Switch,
            {
              checked: Boolean(credValues[field.key]),
              onCheckedChange: (checked) => setCredValues((prev) => ({ ...prev, [field.key]: checked }))
            }
          ) : /* @__PURE__ */ jsx(
            Input,
            {
              type: field.type === "secret" ? "password" : "text",
              placeholder: field.placeholder,
              value: credValues[field.key] ?? "",
              onChange: (e) => setCredValues((prev) => ({ ...prev, [field.key]: e.target.value }))
            }
          )
        ] }, field.key)),
        /* @__PURE__ */ jsxs(Button, { type: "button", onClick: () => void handleSaveCredentials(), disabled: isSavingCreds, children: [
          isSavingCreds ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : null,
          t("integrations.detail.credentials.save")
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsx(CardTitle, { children: t("integrations.bundle.integrationToggles") }),
        /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
          /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => void handleBulkToggle(true), children: t("integrations.marketplace.enableAll") }),
          /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => void handleBulkToggle(false), children: t("integrations.marketplace.disableAll") })
        ] })
      ] }) }),
      /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx("div", { className: "space-y-3", children: detail.bundleIntegrations.map((item) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between rounded-lg border p-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(
            Link,
            {
              href: `/backend/integrations/${encodeURIComponent(item.id)}`,
              className: "text-sm font-medium hover:underline",
              children: item.title
            }
          ),
          item.category && /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "ml-2 text-xs", children: item.category }),
          item.description && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-0.5", children: item.description })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
          /* @__PURE__ */ jsx(Button, { asChild: true, variant: "ghost", size: "sm", children: /* @__PURE__ */ jsx(Link, { href: `/backend/integrations/${encodeURIComponent(item.id)}`, children: t("integrations.bundle.configureIntegration") }) }),
          /* @__PURE__ */ jsx(
            Switch,
            {
              checked: item.isEnabled,
              disabled: togglingIds.has(item.id),
              onCheckedChange: (checked) => void handleToggle(item.id, checked, item.state?.updatedAt)
            }
          )
        ] })
      ] }, item.id)) }) })
    ] })
  ] }) });
}
export {
  BundleConfigPage as default
};
//# sourceMappingURL=page.js.map
