"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import * as React from "react";
import { useMutation } from "@tanstack/react-query";
import { deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { Button } from "@open-mercato/ui/primitives/button";
import { Badge } from "@open-mercato/ui/primitives/badge";
import Link from "next/link";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { ListEmptyState } from "@open-mercato/ui/backend/filters/ListEmptyState";
function FeatureTogglesTable() {
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const queryClient = useQueryClient();
  const featureToggleTypeLabelMap = React.useMemo(() => /* @__PURE__ */ new Map([
    ["boolean", { label: t("feature_toggles.types.boolean", "Boolean"), variant: "default" }],
    ["string", { label: t("feature_toggles.types.string", "String"), variant: "secondary" }],
    ["number", { label: t("feature_toggles.types.number", "Number"), variant: "outline" }],
    ["json", { label: t("feature_toggles.types.json", "JSON"), variant: "destructive" }]
  ]), [t]);
  const [filterValues, setFilterValues] = React.useState({});
  const [sorting, setSorting] = React.useState([]);
  const [pagination, setPagination] = React.useState({ page: 1, pageSize: 25 });
  const categoryFilterValue = typeof filterValues.category === "string" ? filterValues.category.trim() : "";
  const nameFilterValue = typeof filterValues.name === "string" ? filterValues.name.trim() : "";
  const identifierFilterValue = typeof filterValues.identifier === "string" ? filterValues.identifier.trim() : "";
  const typeFilterValue = typeof filterValues.type === "string" ? filterValues.type.trim() : "";
  const sortField = sorting.length > 0 ? sorting[0].id : "category";
  const sortDir = sorting.length > 0 && sorting[0].desc ? "desc" : "asc";
  const queryParams = React.useMemo(() => {
    const params = new URLSearchParams();
    if (categoryFilterValue) params.set("category", categoryFilterValue);
    if (nameFilterValue) params.set("name", nameFilterValue);
    if (identifierFilterValue) params.set("identifier", identifierFilterValue);
    if (typeFilterValue) params.set("type", typeFilterValue);
    params.set("sortField", sortField);
    params.set("sortDir", sortDir);
    params.set("page", pagination.page.toString());
    params.set("pageSize", pagination.pageSize.toString());
    return params.toString();
  }, [categoryFilterValue, identifierFilterValue, nameFilterValue, sortField, sortDir, typeFilterValue, pagination]);
  const handleSortingChange = React.useCallback((newSorting) => {
    setSorting(newSorting);
  }, []);
  const handlePageChange = React.useCallback((page) => {
    setPagination((prev) => ({ ...prev, page }));
  }, []);
  const { data: featureTogglesData, isLoading } = useQuery({
    queryKey: ["feature_toggles", queryParams],
    queryFn: async () => {
      const call = await apiCall(
        `/api/feature_toggles/global${queryParams ? `?${queryParams}` : ""}`
      );
      if (!call.ok) {
        await raiseCrudError(call.response, t("feature_toggles.list.error.load", "Failed to load feature toggles"));
      }
      return call.result ?? { items: [], total: 0, totalPages: 1, page: 1, pageSize: 25 };
    }
  });
  const filters = React.useMemo(() => [
    {
      id: "identifier",
      label: t("feature_toggles.list.filters.identifier", "Identifier"),
      type: "text"
    },
    {
      id: "name",
      label: t("feature_toggles.list.filters.name", "Name"),
      type: "text"
    },
    {
      id: "category",
      label: t("feature_toggles.list.filters.category", "Category"),
      type: "text"
    },
    {
      id: "type",
      label: t("feature_toggles.list.filters.type", "Type"),
      type: "select",
      options: [
        { label: t("feature_toggles.types.boolean", "Boolean"), value: "boolean" },
        { label: t("feature_toggles.types.string", "String"), value: "string" },
        { label: t("feature_toggles.types.number", "Number"), value: "number" },
        { label: t("feature_toggles.types.json", "JSON"), value: "json" }
      ]
    }
  ], [t]);
  const handleFiltersApply = React.useCallback((values) => {
    setFilterValues(values);
  }, []);
  const handleFiltersClear = React.useCallback(() => {
    setFilterValues({});
  }, []);
  const deleteFeatureToggleMutation = useMutation({
    mutationFn: async (row) => {
      await withScopedApiRequestHeaders(
        buildOptimisticLockHeader(row.updatedAt),
        () => deleteCrud("feature_toggles/global", row.id)
      );
    },
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["feature_toggles"] });
    }
  });
  const handleDelete = React.useCallback(async (row) => {
    const confirmed = await confirm({
      title: t("feature_toggles.list.confirmDelete", 'Delete feature toggle "{identifier}"?', { identifier: row.identifier }),
      variant: "destructive"
    });
    if (!confirmed) return;
    await deleteFeatureToggleMutation.mutateAsync(row);
  }, [confirm, deleteFeatureToggleMutation, t]);
  const columns = React.useMemo(() => {
    const base = [
      {
        accessorKey: "category",
        header: t("feature_toggles.list.headers.category", "Category"),
        enableSorting: true,
        cell: ({ row }) => {
          return row.original.category || "-";
        }
      },
      {
        accessorKey: "identifier",
        header: t("feature_toggles.list.headers.identifier", "Identifier"),
        enableSorting: true
      },
      {
        accessorKey: "name",
        header: t("feature_toggles.list.headers.name", "Name"),
        enableSorting: true
      },
      {
        accessorKey: "type",
        header: t("feature_toggles.list.headers.type", "Type"),
        enableSorting: true,
        cell: ({ row }) => {
          const typeInfo = featureToggleTypeLabelMap.get(row.original.type);
          if (!typeInfo) return "-";
          return /* @__PURE__ */ jsx(Badge, { variant: typeInfo.variant, children: typeInfo.label });
        }
      }
    ];
    return base;
  }, [t, featureToggleTypeLabelMap]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("feature_toggles.global.help.title", "Feature Toggles"),
        disableRowClick: true,
        actions: /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/feature-toggles/global/create", children: t("common.create", "Create") }) }),
        columns,
        data: featureTogglesData?.items ?? [],
        isLoading,
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: t("feature_toggles.global.help.title", "Feature Toggles"),
            createHref: "/backend/feature-toggles/global/create",
            createLabel: t("common.create", "Create")
          }
        ),
        filters,
        filterValues,
        onFiltersApply: handleFiltersApply,
        onFiltersClear: handleFiltersClear,
        sorting,
        onSortingChange: handleSortingChange,
        sortable: true,
        pagination: {
          page: featureTogglesData?.page ?? 1,
          pageSize: featureTogglesData?.pageSize ?? 25,
          total: featureTogglesData?.total ?? 0,
          totalPages: featureTogglesData?.totalPages ?? 0,
          onPageChange: handlePageChange
        },
        rowActions: (row) => /* @__PURE__ */ jsx(RowActions, { items: [
          { id: "edit", label: t("common.edit", "Edit"), href: `/backend/feature-toggles/global/${row.id}/edit` },
          { id: "view", label: t("common.view", "Overrides"), href: `/backend/feature-toggles/global/${row.id}` },
          { id: "delete", label: t("common.delete", "Delete"), destructive: true, onSelect: () => {
            void handleDelete(row);
          } }
        ] })
      }
    ),
    ConfirmDialogElement
  ] });
}
export {
  FeatureTogglesTable
};
//# sourceMappingURL=FeatureTogglesTable.js.map
