"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@open-mercato/ui/primitives/card";
import { DataLoader } from "@open-mercato/ui";
import { Alert, AlertDescription, AlertTitle } from "@open-mercato/ui/primitives/alert";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { createOverrideFieldDefinitions, createOverrideFormGroups } from "./overrideFormConfig.js";
function FeatureToggleOverrideCard({ toggleId }) {
  const t = useT();
  const queryClient = useQueryClient();
  const { data: overrideData, isLoading, error } = useQuery({
    queryKey: ["feature_toggle_override", toggleId],
    queryFn: async () => {
      const call = await apiCall(`/api/feature_toggles/global/${toggleId}/override`);
      if (!call.ok) {
        await raiseCrudError(call.response, t("feature_toggles.override.error.load", "Failed to load override"));
      }
      return call.result;
    },
    enabled: !!toggleId
  });
  const mutation = useMutation({
    mutationFn: async (input) => {
      const call = await withScopedApiRequestHeaders(
        buildOptimisticLockHeader(overrideData?.updatedAt ?? null),
        () => apiCall(
          `/api/feature_toggles/overrides`,
          {
            method: "PUT",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({
              toggleId: input.toggleId,
              isOverride: input.isOverride,
              overrideValue: input.overrideValue
            })
          }
        )
      );
      if (!call.ok) {
        await raiseCrudError(call.response, t("feature_toggles.overrides.error.update", "Failed to update override"));
      }
      return call.result;
    },
    onError: (err) => {
      surfaceRecordConflict(err, t);
    },
    onSettled: async () => {
      await queryClient.invalidateQueries({ queryKey: ["feature_toggle_override", toggleId] });
      await queryClient.invalidateQueries({ queryKey: ["feature_toggle_overrides"] });
    }
  });
  if (error) {
    return /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: t("feature_toggles.override.title", "Override") }) }),
      /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsxs(Alert, { variant: "destructive", children: [
        /* @__PURE__ */ jsx(AlertTitle, { children: t("ui.errors.defaultTitle", "Something went wrong") }),
        /* @__PURE__ */ jsx(AlertDescription, { children: error.message })
      ] }) })
    ] });
  }
  const fieldDefinitions = createOverrideFieldDefinitions(t);
  const formGroups = createOverrideFormGroups(t);
  const initialValues = overrideData ? {
    isOverride: overrideData.id === "" ? false : true,
    overrideValue: overrideData.value,
    toggleType: overrideData.toggleType,
    tenantId: overrideData.tenantId,
    tenantName: overrideData.tenantName
  } : {};
  const handleSubmit = async (values) => {
    if (!overrideData) return;
    await mutation.mutateAsync({
      toggleId,
      isOverride: values.isOverride,
      overrideValue: values.overrideValue,
      tenantId: overrideData.tenantId
    });
  };
  return /* @__PURE__ */ jsxs(Card, { children: [
    /* @__PURE__ */ jsxs(CardHeader, { children: [
      /* @__PURE__ */ jsx(CardTitle, { children: t("feature_toggles.override.title", "Override") }),
      overrideData ? /* @__PURE__ */ jsx(CardDescription, { children: t("feature_toggles.override.tenant", "Tenant: {{name}}", { name: overrideData.tenantName }) }) : /* @__PURE__ */ jsx(CardDescription, { className: "h-5 w-48 animate-pulse bg-zinc-100 dark:bg-zinc-800 rounded-md" })
    ] }),
    /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(
      DataLoader,
      {
        isLoading,
        showSkeleton: true,
        skeletonComponent: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsx("div", { className: "h-9 w-full animate-pulse rounded-md bg-zinc-100 dark:bg-zinc-800" }),
          /* @__PURE__ */ jsx("div", { className: "h-20 w-full animate-pulse rounded-md bg-zinc-100 dark:bg-zinc-800" })
        ] }),
        children: overrideData && /* @__PURE__ */ jsx(
          CrudForm,
          {
            fields: fieldDefinitions,
            groups: formGroups,
            initialValues,
            onSubmit: handleSubmit,
            submitLabel: t("feature_toggles.override.save", "Save Override"),
            embedded: true,
            isLoading: false
          }
        )
      }
    ) })
  ] });
}
export {
  FeatureToggleOverrideCard
};
//# sourceMappingURL=FeatureToggleOverrideCard.js.map
