import { j as jsxRuntimeExports } from "../../../../../../../_virtual/jsx-runtime.js";
import { Fragment } from "react";
import "../../../../../../../node_modules/.pnpm/@formkit_auto-animate@0.8.2/node_modules/@formkit/auto-animate/index.js";
import "../../../../../../../node_modules/.pnpm/react-hot-toast@2.5.2_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/react-hot-toast/dist/index.js";
import { tx as D } from "../../../../../../style-system/dist/twind.js";
import { RxCross2 } from "../../../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/rx/index.js";
import { useDatasources, useDatasource } from "../../../hooks/use-datasource.js";
import { TbPlus } from "../../../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/tb/index.js";
import { FieldTitle } from "../field-factory.js";
import debounce from "../../../../../../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/debounce.js";
import { Root as C, Trigger as u, Content as g, Item as v, Group as y, Separator as I } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/select.js";
import { Button as o } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/button.js";
import { IconButton as o$1 } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/icon-button.js";
import { Root as u$1 } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/text-field.js";
import { Root as p, Item as l } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/segmented-control.js";
function getDatasourceIndexedFieldsWithTitles(datasource) {
  if ("indexes" in datasource === false) {
    console.error("no datasource or indexes found", datasource);
    return [];
  }
  const properties = datasource.schema?.items?.properties || {};
  const uniqueFields = Array.from(new Set(datasource.indexes?.map((idx) => idx.fields[0]) ?? []));
  return uniqueFields.map((field) => ({
    value: field,
    title: properties[field]?.title || field
  }));
}
const DatasourceField = (props) => {
  const { currentValue, onChange, formData, formSchema } = props;
  const datasources = useDatasources();
  const datasource = useDatasource(currentValue?.id);
  const handleChange = (field, value) => {
    const newValue = { ...currentValue ?? {}, [field]: value };
    console.log("DatasourceField handleChange", newValue);
    onChange(newValue);
  };
  const indexedFields = datasource ? getDatasourceIndexedFieldsWithTitles(datasource) : [];
  const sortableFields = indexedFields.filter((field) => ["$id", "$slug"].includes(field.value) === false);
  const filters = currentValue?.filters ?? [];
  const getOperatorOptionsForField = (fieldName) => {
    if (!datasource) return [];
    const fieldType = getFieldType(fieldName);
    const baseOperators = [
      { value: "eq", label: "Equals" },
      { value: "ne", label: "Not equals" }
    ];
    const stringOperators = [
      { value: "contains", label: "Contains" },
      { value: "notContains", label: "Not contains" },
      { value: "startsWith", label: "Starts with" },
      { value: "notStartsWith", label: "Not starts with" },
      { value: "endsWith", label: "Ends with" },
      { value: "notEndsWith", label: "Not ends with" }
    ];
    const arrayOperators = [
      { value: "contains", label: "Contains" },
      { value: "notContains", label: "Not contains" },
      { value: "containsAll", label: "Contains all" },
      { value: "containsAny", label: "Contains any" },
      { value: "notContainsAny", label: "Not contains any" }
    ];
    const numberOperators = [
      { value: "lt", label: "Less than" },
      { value: "lte", label: "Less than or equal" },
      { value: "gt", label: "Greater than" },
      { value: "gte", label: "Greater than or equal" }
    ];
    const dateOperators = [
      { value: "before", label: "Before Date" },
      { value: "after", label: "After Date" },
      { value: "$beforeNow", label: "Before Now" },
      { value: "$afterNow", label: "After Now" }
    ];
    switch (fieldType) {
      case "array":
        return arrayOperators;
      case "string":
        return [...baseOperators, ...stringOperators];
      case "number":
      case "integer":
        return [...baseOperators, ...numberOperators];
      case "boolean":
        return [{ value: "eq", label: "Equals" }];
      case "date":
      case "datetime":
        return [...dateOperators, baseOperators[0]];
      default:
        return [...baseOperators, ...stringOperators, ...numberOperators, ...dateOperators];
    }
  };
  const addFilter = () => {
    const newFilters = [...filters, { field: "", op: "eq", value: "" }];
    handleChange("filters", newFilters);
  };
  const removeFilter = (index) => {
    const newFilters = filters.filter((_, i) => i !== index);
    handleChange("filters", newFilters);
  };
  const updateFilter = (index, key, value) => {
    const newFilters = [...filters];
    const currentFilter = { ...newFilters[index] };
    if (key === "field") {
      const op = value ? getOperatorOptionsForField(value)[0].value : "eq";
      newFilters[index] = { field: value, op, value: "" };
    } else if (key === "op") {
      newFilters[index] = { ...currentFilter, op: value, value: "" };
    } else {
      newFilters[index] = { ...currentFilter, [key]: value };
    }
    handleChange("filters", newFilters);
  };
  const getFieldType = (fieldName) => {
    if (!datasource) return "string";
    const property = datasource.schema?.items?.properties?.[fieldName];
    if (property?.type === "string" && property.format === "date") return "date";
    if (property?.type === "string" && property.format === "date-time") return "datetime";
    return property?.type ?? "string";
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-3 flex-1 -mx-2.5 divide-y divide-gray-200", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex justify-between gap-10 flex-1 items-center py-0.5 px-2.5", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { title: "Database", description: "Select a database to query" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        C,
        {
          defaultValue: currentValue?.id,
          size: "2",
          onValueChange: (value) => handleChange("id", value),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              u,
              {
                radius: "medium",
                variant: "ghost",
                placeholder: "Select a database",
                className: "!max-w-2/3 !ml-auto !mr-[1px]"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(g, { position: "popper", children: datasources.map((ds) => /* @__PURE__ */ jsxRuntimeExports.jsx(v, { value: ds.id, children: ds.label }, ds.id)) })
          ]
        }
      )
    ] }),
    indexedFields.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-2 flex-1 justify-between pt-2.5 px-2.5", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex gap-1 flex-1 w-full justify-between items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { title: "Filters", description: "Add filters to narrow down your query" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(o, { type: "button", radius: "full", variant: "soft", size: "1", onClick: addFilter, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(TbPlus, { className: "w-3 h-3" }),
          "Add Filter"
        ] })
      ] }),
      filters.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "basis-full flex flex-col gap-3 mt-1", children: filters.map((filter, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid grid-cols-5 gap-x-2 gap-y-0.5 auto-rows-[30px]", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "col-span-5 flex items-center gap-3 pr-1", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              o$1,
              {
                size: "1",
                type: "button",
                variant: "ghost",
                className: "hover:(bg-red-100 text-red-800) !shrink-0",
                onClick: () => removeFilter(index),
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(RxCross2, { size: 14 })
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              C,
              {
                defaultValue: filter.field,
                onValueChange: (value) => updateFilter(index, "field", value),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    u,
                    {
                      radius: "medium",
                      className: "!flex-1 !font-medium",
                      variant: "ghost",
                      placeholder: "Select field"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(g, { position: "popper", children: /* @__PURE__ */ jsxRuntimeExports.jsx(y, { children: indexedFields.map((field) => /* @__PURE__ */ jsxRuntimeExports.jsx(v, { value: field.value, children: field.title }, field.value)) }) })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: D("flex gap-2 items-center col-span-2", !filter.field && "hidden"), children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            C,
            {
              defaultValue: filter.op,
              size: "2",
              onValueChange: (value) => updateFilter(index, "op", value),
              disabled: !filter.field,
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  u,
                  {
                    radius: "medium",
                    variant: "ghost",
                    placeholder: "Select operator",
                    className: "!flex-1 !mr-1"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(g, { position: "popper", children: /* @__PURE__ */ jsxRuntimeExports.jsx(y, { children: getOperatorOptionsForField(filter.field).map((option) => /* @__PURE__ */ jsxRuntimeExports.jsx(v, { value: option.value, children: option.label }, option.value)) }) })
              ]
            },
            `operator-${index}-${filter.field}`
          ) }),
          getFieldType(filter.field) === "date" || getFieldType(filter.field) === "datetime" ? (filter.op === "before" || filter.op === "after" || filter.op === "eq") && // Absolute date: span both columns
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: D("col-span-3 flex justify-end", !filter.field && "hidden"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            u$1,
            {
              size: "2",
              type: getFieldType(filter.field) === "datetime" ? "datetime-local" : "date",
              defaultValue: String(filter.value),
              onChange: (e) => updateFilter(index, "value", e.target.value),
              disabled: !filter.field,
              className: "!w-full"
            }
          ) }) : (
            // Non-date fields: span both columns
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: D("col-span-3 flex justify-end ", !filter.field && "hidden"), children: getFieldType(filter.field) === "number" || getFieldType(filter.field) === "integer" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              u$1,
              {
                type: "number",
                size: "2",
                defaultValue: String(filter.value),
                onChange: (e) => updateFilter(index, "value", Number(e.target.value)),
                placeholder: "Value",
                min: "1",
                disabled: !filter.field,
                className: "!w-full"
              }
            ) : getFieldType(filter.field) === "boolean" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
              p,
              {
                size: "1",
                defaultValue: String(filter.value),
                onValueChange: (value) => updateFilter(index, "value", Boolean(value)),
                className: D("!mt-0.5 [&_.rt-SegmentedControlItemLabel]:(px-3)"),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(l, { value: "true", children: "True" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(l, { value: "false", children: "False" })
                ]
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              u$1,
              {
                disabled: !filter.field,
                defaultValue: String(filter.value),
                onChange: debounce((e) => updateFilter(index, "value", e.target.value), 400),
                placeholder: "Value",
                size: "2",
                className: "!w-full"
              }
            ) })
          )
        ] }),
        index < filters.length - 1 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "border-t border-gray-200 my-2 relative", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "absolute left-1/2 -translate-x-1/2 -top-3 bg-white px-2 py-1 inline-block text-xs text-gray-500", children: "And" }) })
      ] }, index)) })
    ] }),
    currentValue?.id && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-1 gap-8 justify-between items-center pt-2.5 pb-1 px-2.5", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-1 flex-1 ", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { title: "Order by", description: "Select a field to sort the results" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          C,
          {
            defaultValue: currentValue?.sortField,
            size: "2",
            onValueChange: (value) => handleChange("sortField", value),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(u, { radius: "medium", variant: "ghost", placeholder: "Select a field" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(g, { position: "popper", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(y, { children: sortableFields.map((field) => /* @__PURE__ */ jsxRuntimeExports.jsx(v, { value: field.value, children: field.title }, field.value)) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(I, {}),
                /* @__PURE__ */ jsxRuntimeExports.jsx(y, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(v, { value: "random()", children: "Random" }) })
              ] })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: D(
            "flex flex-col gap-1 flex-1",
            currentValue?.sortField === "random()" && "opacity-40"
          ),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(FieldTitle, { title: "Direction", description: "Select the direction to sort the results" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              C,
              {
                disabled: currentValue?.sortField === "random()",
                defaultValue: currentValue?.sortDirection || "asc",
                size: "2",
                onValueChange: (value) => handleChange("sortDirection", value),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    u,
                    {
                      radius: "medium",
                      variant: "ghost",
                      placeholder: "Select direction",
                      className: "!mr-[1px]"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(g, { position: "popper", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(y, { children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(v, { value: "asc", children: "Ascending" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(v, { value: "desc", children: "Descending" })
                  ] }) })
                ]
              }
            )
          ]
        }
      )
    ] }),
    currentValue?.id && indexedFields.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex flex-1 justify-between items-center pt-2 px-2.5", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        FieldTitle,
        {
          title: "Number of items",
          description: "If greater than 1, all children bricks will be repeated"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        u$1,
        {
          type: "number",
          value: currentValue?.limit?.toString() ?? "10",
          onChange: (e) => handleChange("limit", parseInt(e.target.value) || 10),
          min: "1",
          max: "30",
          className: "!w-[40px]"
        }
      )
    ] })
  ] });
};
export {
  DatasourceField as default
};
//# sourceMappingURL=datasource.js.map
