import { j as e } from "../../../../../../../_virtual/jsx-runtime.js";
import { Fragment as I } 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@18.3.0-canary-3d9b20132-20240124_react@18.3.0-canary-3d_c02c1e17bf76c343fd22d1f22394ecf5/node_modules/react-hot-toast/dist/index.js";
import { tx as x } from "../../../../../../style-system/dist/twind.js";
import { RxCross2 as O } from "../../../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/rx/index.js";
import { useDatasources as $, useDatasource as T } from "../../../hooks/use-datasource.js";
import { TbPlus as R } from "../../../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/tb/index.js";
import { FieldTitle as h } from "../field-factory.js";
import B from "../../../../../../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/debounce.js";
import { Root as f, Trigger as v, Content as g, Item as o, Group as j, Separator as E } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/select.js";
import { Button as W } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/button.js";
import { IconButton as k } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/icon-button.js";
import { Root as w } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/text-field.js";
import { Root as G, Item as V } from "../../../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/segmented-control.js";
function L(d) {
  if (!("indexes" in d))
    return console.error("no datasource or indexes found", d), [];
  const t = d.schema?.items?.properties || {};
  return Array.from(new Set(d.indexes?.map((c) => c.fields[0]) ?? [])).map((c) => ({
    value: c,
    title: t[c]?.title || c
  }));
}
const re = (d) => {
  const { currentValue: t, onChange: C, formData: c, formSchema: _ } = d, q = $(), m = T(t?.id), i = (a, s) => {
    const l = { ...t ?? {}, [a]: s };
    console.log("DatasourceField handleChange", l), C(l);
  }, b = m ? L(m) : [], D = b.filter((a) => ["$id", "$slug"].includes(a.value) === !1), u = t?.filters ?? [], F = (a) => {
    if (!m) return [];
    const s = n(a), l = [
      { value: "eq", label: "Equals" },
      { value: "ne", label: "Not equals" }
    ], r = [
      { 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" }
    ], N = [
      { 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" }
    ], y = [
      { value: "lt", label: "Less than" },
      { value: "lte", label: "Less than or equal" },
      { value: "gt", label: "Greater than" },
      { value: "gte", label: "Greater than or equal" }
    ], S = [
      { value: "before", label: "Before Date" },
      { value: "after", label: "After Date" },
      { value: "$beforeNow", label: "Before Now" },
      { value: "$afterNow", label: "After Now" }
    ];
    switch (s) {
      case "array":
        return N;
      case "string":
        return [...l, ...r];
      case "number":
      case "integer":
        return [...l, ...y];
      case "boolean":
        return [{ value: "eq", label: "Equals" }];
      case "date":
      case "datetime":
        return [...S, l[0]];
      default:
        return [...l, ...r, ...y, ...S];
    }
  }, z = () => {
    const a = [...u, { field: "", op: "eq", value: "" }];
    i("filters", a);
  }, A = (a) => {
    const s = u.filter((l, r) => r !== a);
    i("filters", s);
  }, p = (a, s, l) => {
    const r = [...u], N = { ...r[a] };
    if (s === "field") {
      const y = l ? F(l)[0].value : "eq";
      r[a] = { field: l, op: y, value: "" };
    } else s === "op" ? r[a] = { ...N, op: l, value: "" } : r[a] = { ...N, [s]: l };
    i("filters", r);
  }, n = (a) => {
    if (!m) return "string";
    const s = m.schema?.items?.properties?.[a];
    return s?.type === "string" && s.format === "date" ? "date" : s?.type === "string" && s.format === "date-time" ? "datetime" : s?.type ?? "string";
  };
  return /* @__PURE__ */ e.jsxs("div", { className: "flex flex-col gap-3 flex-1 -mx-2.5 divide-y divide-gray-200", children: [
    /* @__PURE__ */ e.jsxs("div", { className: "flex justify-between gap-10 flex-1 items-center py-0.5 px-2.5", children: [
      /* @__PURE__ */ e.jsx(h, { title: "Database", description: "Select a database to query" }),
      /* @__PURE__ */ e.jsxs(
        f,
        {
          defaultValue: t?.id,
          size: "2",
          onValueChange: (a) => i("id", a),
          children: [
            /* @__PURE__ */ e.jsx(
              v,
              {
                radius: "medium",
                variant: "ghost",
                placeholder: "Select a database",
                className: "!max-w-2/3 !ml-auto !mr-[1px]"
              }
            ),
            /* @__PURE__ */ e.jsx(g, { position: "popper", children: q.map((a) => /* @__PURE__ */ e.jsx(o, { value: a.id, children: a.label }, a.id)) })
          ]
        }
      )
    ] }),
    b.length > 0 && /* @__PURE__ */ e.jsxs("div", { className: "flex flex-col gap-2 flex-1 justify-between pt-2.5 px-2.5", children: [
      /* @__PURE__ */ e.jsxs("div", { className: "flex gap-1 flex-1 w-full justify-between items-center", children: [
        /* @__PURE__ */ e.jsx(h, { title: "Filters", description: "Add filters to narrow down your query" }),
        /* @__PURE__ */ e.jsxs(W, { type: "button", radius: "full", variant: "soft", size: "1", onClick: z, children: [
          /* @__PURE__ */ e.jsx(R, { className: "w-3 h-3" }),
          "Add Filter"
        ] })
      ] }),
      u.length > 0 && /* @__PURE__ */ e.jsx("div", { className: "basis-full flex flex-col gap-3 mt-1", children: u.map((a, s) => /* @__PURE__ */ e.jsxs(I, { children: [
        /* @__PURE__ */ e.jsxs("div", { className: "grid grid-cols-5 gap-x-2 gap-y-0.5 auto-rows-[30px]", children: [
          /* @__PURE__ */ e.jsxs("div", { className: "col-span-5 flex items-center gap-3 pr-1", children: [
            /* @__PURE__ */ e.jsx(
              k,
              {
                size: "1",
                type: "button",
                variant: "ghost",
                className: "hover:(bg-red-100 text-red-800) !shrink-0",
                onClick: () => A(s),
                children: /* @__PURE__ */ e.jsx(O, { size: 14 })
              }
            ),
            /* @__PURE__ */ e.jsxs(
              f,
              {
                defaultValue: a.field,
                onValueChange: (l) => p(s, "field", l),
                children: [
                  /* @__PURE__ */ e.jsx(
                    v,
                    {
                      radius: "medium",
                      className: "!flex-1 !font-medium",
                      variant: "ghost",
                      placeholder: "Select field"
                    }
                  ),
                  /* @__PURE__ */ e.jsx(g, { position: "popper", children: /* @__PURE__ */ e.jsx(j, { children: b.map((l) => /* @__PURE__ */ e.jsx(o, { value: l.value, children: l.title }, l.value)) }) })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ e.jsx("div", { className: x("flex gap-2 items-center col-span-2", !a.field && "hidden"), children: /* @__PURE__ */ e.jsxs(
            f,
            {
              defaultValue: a.op,
              size: "2",
              onValueChange: (l) => p(s, "op", l),
              disabled: !a.field,
              children: [
                /* @__PURE__ */ e.jsx(
                  v,
                  {
                    radius: "medium",
                    variant: "ghost",
                    placeholder: "Select operator",
                    className: "!flex-1 !mr-1"
                  }
                ),
                /* @__PURE__ */ e.jsx(g, { position: "popper", children: /* @__PURE__ */ e.jsx(j, { children: F(a.field).map((l) => /* @__PURE__ */ e.jsx(o, { value: l.value, children: l.label }, l.value)) }) })
              ]
            },
            `operator-${s}-${a.field}`
          ) }),
          n(a.field) === "date" || n(a.field) === "datetime" ? (a.op === "before" || a.op === "after" || a.op === "eq") && // Absolute date: span both columns
          /* @__PURE__ */ e.jsx("div", { className: x("col-span-3 flex justify-end", !a.field && "hidden"), children: /* @__PURE__ */ e.jsx(
            w,
            {
              size: "2",
              type: n(a.field) === "datetime" ? "datetime-local" : "date",
              defaultValue: String(a.value),
              onChange: (l) => p(s, "value", l.target.value),
              disabled: !a.field,
              className: "!w-full"
            }
          ) }) : (
            // Non-date fields: span both columns
            /* @__PURE__ */ e.jsx("div", { className: x("col-span-3 flex justify-end ", !a.field && "hidden"), children: n(a.field) === "number" || n(a.field) === "integer" ? /* @__PURE__ */ e.jsx(
              w,
              {
                type: "number",
                size: "2",
                defaultValue: String(a.value),
                onChange: (l) => p(s, "value", Number(l.target.value)),
                placeholder: "Value",
                min: "1",
                disabled: !a.field,
                className: "!w-full"
              }
            ) : n(a.field) === "boolean" ? /* @__PURE__ */ e.jsxs(
              G,
              {
                size: "1",
                defaultValue: String(a.value),
                onValueChange: (l) => p(s, "value", !!l),
                className: x("!mt-0.5 [&_.rt-SegmentedControlItemLabel]:(px-3)"),
                children: [
                  /* @__PURE__ */ e.jsx(V, { value: "true", children: "True" }),
                  /* @__PURE__ */ e.jsx(V, { value: "false", children: "False" })
                ]
              }
            ) : /* @__PURE__ */ e.jsx(
              w,
              {
                disabled: !a.field,
                defaultValue: String(a.value),
                onChange: B((l) => p(s, "value", l.target.value), 400),
                placeholder: "Value",
                size: "2",
                className: "!w-full"
              }
            ) })
          )
        ] }),
        s < u.length - 1 && /* @__PURE__ */ e.jsx("div", { className: "border-t border-gray-200 my-2 relative", children: /* @__PURE__ */ e.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" }) })
      ] }, s)) })
    ] }),
    t?.id && /* @__PURE__ */ e.jsxs("div", { className: "flex flex-1 gap-8 justify-between items-center pt-2.5 pb-1 px-2.5", children: [
      /* @__PURE__ */ e.jsxs("div", { className: "flex flex-col gap-1 flex-1 ", children: [
        /* @__PURE__ */ e.jsx(h, { title: "Order by", description: "Select a field to sort the results" }),
        /* @__PURE__ */ e.jsxs(
          f,
          {
            defaultValue: t?.sortField,
            size: "2",
            onValueChange: (a) => i("sortField", a),
            children: [
              /* @__PURE__ */ e.jsx(v, { radius: "medium", variant: "ghost", placeholder: "Select a field" }),
              /* @__PURE__ */ e.jsxs(g, { position: "popper", children: [
                /* @__PURE__ */ e.jsx(j, { children: D.map((a) => /* @__PURE__ */ e.jsx(o, { value: a.value, children: a.title }, a.value)) }),
                /* @__PURE__ */ e.jsx(E, {}),
                /* @__PURE__ */ e.jsx(j, { children: /* @__PURE__ */ e.jsx(o, { value: "random()", children: "Random" }) })
              ] })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ e.jsxs(
        "div",
        {
          className: x(
            "flex flex-col gap-1 flex-1",
            t?.sortField === "random()" && "opacity-40"
          ),
          children: [
            /* @__PURE__ */ e.jsx(h, { title: "Direction", description: "Select the direction to sort the results" }),
            /* @__PURE__ */ e.jsxs(
              f,
              {
                disabled: t?.sortField === "random()",
                defaultValue: t?.sortDirection || "asc",
                size: "2",
                onValueChange: (a) => i("sortDirection", a),
                children: [
                  /* @__PURE__ */ e.jsx(
                    v,
                    {
                      radius: "medium",
                      variant: "ghost",
                      placeholder: "Select direction",
                      className: "!mr-[1px]"
                    }
                  ),
                  /* @__PURE__ */ e.jsx(g, { position: "popper", children: /* @__PURE__ */ e.jsxs(j, { children: [
                    /* @__PURE__ */ e.jsx(o, { value: "asc", children: "Ascending" }),
                    /* @__PURE__ */ e.jsx(o, { value: "desc", children: "Descending" })
                  ] }) })
                ]
              }
            )
          ]
        }
      )
    ] }),
    t?.id && b.length > 0 && /* @__PURE__ */ e.jsxs("div", { className: "flex flex-1 justify-between items-center pt-2 px-2.5", children: [
      /* @__PURE__ */ e.jsx(
        h,
        {
          title: "Number of items",
          description: "If greater than 1, all children bricks will be repeated"
        }
      ),
      /* @__PURE__ */ e.jsx(
        w,
        {
          type: "number",
          value: t?.limit?.toString() ?? "10",
          onChange: (a) => i("limit", parseInt(a.target.value) || 10),
          min: "1",
          max: "30",
          className: "!w-[40px]"
        }
      )
    ] })
  ] });
};
export {
  re as default
};
//# sourceMappingURL=datasource.js.map
