import { j as e } from "../../../../../../../_virtual/jsx-runtime.js";
import { b as Z } from "../../../../../../sdk/dist/shared/chunk-YBGPPF7T.js";
import "@sinclair/typebox";
import "../../../../../../sdk/dist/shared/chunk-5N6MBJJ4.js";
import { useState as A, startTransition as J, useCallback as K, Fragment as X } 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 { BsDatabaseAdd as ee, BsDatabaseDown as ae, BsAt as se, BsCrosshair as te } from "../../../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/bs/index.js";
import { FieldTitle as S } from "../field-factory.js";
import { useSiteQueries as T, useSiteQuery as le, usePagePathParams as re } from "../../../../../../../use-page-data.js";
import { useDatasources as ie, useDatasource as ne } from "../../../hooks/use-datasource.js";
import { FiEdit as oe } from "../../../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/fi/index.js";
import { tx as q } from "../../../../../../style-system/dist/twind.js";
import { LuPlus as ce } from "../../../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/lu/index.js";
import { a as F } from "../../../../../../sdk/dist/shared/chunk-ZTDUXSWH.js";
import "../../../../../../sdk/dist/shared/chunk-T3LIA4YB.js";
import "../../../../../../sdk/dist/shared/chunk-UMHXXXVP.js";
import de, { TagsSelect as ue } from "../../TagsInput.js";
import { Button as P } 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 { Root as me, Content as fe, Title as xe, Description as pe } 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/dialog.js";
import { Tooltip as L } 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/tooltip.js";
import { IconButton as he } 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 D, Trigger as R, Content as k, Group as M, Label as ge, Item 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/select.js";
import { Root as O } 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 be, Item as G } 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";
const C = [
  { value: "eq", label: "Equals" },
  { value: "ne", label: "Not equals" }
], Q = [
  { 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" }
], U = [{ value: "eq", label: "Equals" }], _ = [
  { 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" }
], z = [
  { value: "lt", label: "Less than" },
  { value: "lte", label: "Less than or equal" },
  { value: "gt", label: "Greater than" },
  { value: "gte", label: "Greater than or equal" }
], E = [
  { value: "before", label: "Before Date" },
  { value: "after", label: "After Date" },
  { value: "beforeNow", label: "Before Now" },
  { value: "afterNow", label: "After Now" }
];
function je(r) {
  return [
    ...C,
    ...Q,
    ...U,
    ..._,
    ...z,
    ...E
  ].find((h) => h.value === r)?.label;
}
function ve(r) {
  return typeof r == "string" ? r : Array.isArray(r) ? r.join(", ") : "";
}
const He = (r) => {
  const { currentValue: u = [], onChange: h, schema: I, title: l, description: c, brickId: f } = r, m = ie(), x = T(), [o, g] = A(!1);
  return m.length ? /* @__PURE__ */ e.jsxs(e.Fragment, { children: [
    /* @__PURE__ */ e.jsx(
      ye,
      {
        onChange: h,
        queries: u,
        open: o,
        onClose: () => g(!1)
      }
    ),
    /* @__PURE__ */ e.jsxs("div", { className: "query-field flex items-center justify-between flex-1", children: [
      /* @__PURE__ */ e.jsx(S, { title: l, description: c }),
      x.length > 0 && /* @__PURE__ */ e.jsx(
        P,
        {
          variant: "soft",
          size: "1",
          radius: "full",
          type: "button",
          onClick: () => {
            g(!0);
          },
          children: "Manage page queries"
        }
      )
    ] }),
    /* @__PURE__ */ e.jsxs("div", { className: "basis-full flex flex-col gap-2", children: [
      x.length === 0 && /* @__PURE__ */ e.jsx("div", { className: "text-sm text-gray-500", children: "No queries available. Create a query first so you can use it in this page." }),
      u.length > 0 && /* @__PURE__ */ e.jsx("ul", { className: "list-none p-0 m-0 mt-2", children: u.map((i, n) => /* @__PURE__ */ e.jsxs("li", { className: "flex items-center gap-1.5 mb-2", children: [
        /* @__PURE__ */ e.jsx(ee, {}),
        x.find((v) => v.id === i.queryId)?.label,
        " ",
        /* @__PURE__ */ e.jsxs("span", { className: "text-gray-500 text-xs", children: [
          "(",
          i.alias,
          ")"
        ] })
      ] }, n)) })
    ] })
  ] }) : /* @__PURE__ */ e.jsxs("div", { className: "field field-query basis-full", children: [
    /* @__PURE__ */ e.jsx(S, { title: l, description: c }),
    /* @__PURE__ */ e.jsx("div", { className: "text-sm text-gray-500", children: "No datasources available. Create a datasource first so you can create queries." })
  ] });
};
function ye({
  queries: r,
  open: u,
  onClose: h,
  onChange: I
}) {
  const l = T(), [c, f] = A(r.length === 0), [m, x] = A(null), [o, g] = A(r);
  return /* @__PURE__ */ e.jsx(
    me,
    {
      open: u,
      onOpenChange: (i) => {
        i || h?.();
      },
      children: /* @__PURE__ */ e.jsxs(
        fe,
        {
          "aria-describedby": "Queries managament",
          maxWidth: "760px",
          minHeight: "80dvh",
          className: "overflow-y-clip flex flex-col gap-y-2",
          children: [
            /* @__PURE__ */ e.jsxs(xe, { className: "flex items-center gap-3 pl-0 -ml-3", children: [
              /* @__PURE__ */ e.jsx(ae, { className: "h-6 w-6 text-upstart-600" }),
              "Page queries",
              o.length < 5 && /* @__PURE__ */ e.jsxs(
                P,
                {
                  size: "2",
                  variant: "outline",
                  radius: "medium",
                  className: q("!ml-auto", c && "!opacity-0"),
                  onClick: () => {
                    x(null), f(!0);
                  },
                  children: [
                    /* @__PURE__ */ e.jsx(ce, { className: "w-4 h-4" }),
                    "Add Query"
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ e.jsx(pe, { children: "Page queries can be used for fetching dynamic content and use it in your page. You can specify parameters for queries that accept them. Up to 5 queries can be set for a page." }),
            c && /* @__PURE__ */ e.jsx(
              Ne,
              {
                showCancelBtn: r.length > 0,
                query: m,
                onChange: (i) => {
                  g((n) => n.filter((v) => v.alias !== i.alias).concat(i)), f(!1), J(() => {
                    I(o);
                  });
                },
                onClose: () => f(!1)
              }
            ),
            o.length > 0 && /* @__PURE__ */ e.jsx("div", { className: "flex flex-col border border-gray-200 rounded-lg overflow-hidden -mx-1 mt-3 shadow-sm", children: o.map((i) => /* @__PURE__ */ e.jsxs(
              "div",
              {
                className: "flex items-center justify-between p-4 [&:not(:last-child)]:border-b border-gray-200 ",
                children: [
                  /* @__PURE__ */ e.jsxs("div", { className: "flex flex-col gap-2", children: [
                    /* @__PURE__ */ e.jsx("span", { className: "font-medium", children: l.find((n) => n.id === i.queryId)?.label }),
                    /* @__PURE__ */ e.jsxs("div", { className: "flex gap-6 items-center justify-start text-sm  text-gray-500", children: [
                      /* @__PURE__ */ e.jsx(L, { content: "Alias", children: /* @__PURE__ */ e.jsxs("span", { className: "inline-flex gap-1 items-center cursor-help", children: [
                        /* @__PURE__ */ e.jsx(se, { className: "text-upstart-500" }),
                        i.alias
                      ] }) }),
                      (i.params?.length ?? 0) > 0 && /* @__PURE__ */ e.jsx(L, { content: "Parameters", children: /* @__PURE__ */ e.jsxs("span", { className: "inline-flex gap-1 items-center cursor-help", children: [
                        /* @__PURE__ */ e.jsx(te, { className: "text-upstart-500" }),
                        i.params?.map((n) => /* @__PURE__ */ e.jsxs("div", { className: "inline-flex gap-1 items-center", children: [
                          /* @__PURE__ */ e.jsx("span", { className: "font-medium", children: n.field }),
                          /* @__PURE__ */ e.jsx("span", { children: je(n.op)?.toLocaleLowerCase() }),
                          /* @__PURE__ */ e.jsx("span", { className: "font-medium", children: ve(n.value) })
                        ] }, n.field))
                      ] }) })
                    ] })
                  ] }),
                  /* @__PURE__ */ e.jsx(
                    he,
                    {
                      size: "2",
                      variant: "soft",
                      color: "violet",
                      onClick: () => {
                        x(i), f(!0);
                      },
                      children: /* @__PURE__ */ e.jsx(oe, { className: "w-4 h-4" })
                    }
                  )
                ]
              },
              i.queryId
            )) })
          ]
        }
      )
    }
  );
}
function Ne({
  query: r,
  onClose: u,
  showCancelBtn: h,
  onChange: I
}) {
  const [l, c] = A(
    r ?? {
      params: []
    }
  ), f = le(l?.queryId), m = f?.parameters ?? [], x = () => {
    c({
      params: []
    });
  }, o = ne(f?.datasourceId), g = T(), i = re(), n = () => F.validate(Z, l) && v(), v = () => {
    for (const a of m) {
      const t = o?.schema?.items?.properties?.[a];
      if (t) {
        const s = l.params?.find((d) => d.field === a)?.value, j = F.validate(t, s);
        if (console.log(`Validating param ${a}:`, { valid: j, value: s, schema: t }), !j)
          return !1;
      }
    }
    return !0;
  }, $ = (a) => {
    if (!o) return [];
    switch (p(a)) {
      case "array":
        return _;
      case "nanoid":
        return U;
      case "string":
        return [...C, ...Q];
      case "number":
      case "integer":
        return [...C, ...z];
      case "boolean":
        return [{ value: "eq", label: "Equals" }];
      case "date":
      case "datetime":
        return [...E, C[0]];
      default:
        return [...C, ...Q, ...z, ...E];
    }
  }, b = (a, t, s) => {
    console.log("Updating param:", { name: a, key: t, value: s }), c((j) => {
      const d = [...j?.params ?? []], B = d.find((w) => w.field === a) ?? {
        field: a,
        op: "eq",
        value: ""
      }, V = d.findIndex((w) => w.field === a);
      if (V === -1)
        return console.warn("Current param not found:", { name: a, key: t, value: s }), console.warn("Current params:", d), j;
      if (t === "field") {
        const w = s ? $(s)[0]?.value ?? "eq" : "eq";
        d[V] = { field: s, op: w, value: "" };
      } else t === "op" ? d[V] = {
        ...B,
        op: s,
        value: ""
      } : d[V] = { ...B, [t]: s };
      return console.log("Updated params:", d), {
        ...j,
        params: d
      };
    });
  }, p = (a) => {
    if (!o) return "string";
    const t = o.schema?.items?.properties?.[a];
    return t?.type === "string" && t.format === "date" ? "date" : t?.type === "string" && t.format === "date-time" ? "datetime" : t?.type === "string" && t.format === "nanoid" ? "nanoid" : t?.type ?? "string";
  };
  function H(a) {
    return o?.schema?.items?.properties?.[a].title ?? "";
  }
  function y(a) {
    return l.params?.find((t) => t.field === a)?.op ?? "eq";
  }
  function N(a, t = "") {
    return console.log("Getting field value:", { paramName: a, params: l.params }), l.params?.find((s) => s.field === a)?.value ?? t;
  }
  const Y = K(() => {
    console.log("Submitting query:", l), n() ? (I(l), u?.()) : console.error("Query validation failed:", F.errors, l);
  }, [l]);
  return /* @__PURE__ */ e.jsxs("div", { className: "text-sm border border-gray-300 bg-gray-50 p-4 rounded-lg -mx-1 mt-3 shadow-sm", children: [
    /* @__PURE__ */ e.jsx("h3", { className: "font-bold text-base mb-3", children: r ? "Edit query" : "Add query to use" }),
    /* @__PURE__ */ e.jsxs("div", { className: "flex flex-col text-sm gap-4 flex-1 -mx-2.5 divide-y divide-gray-200", children: [
      /* @__PURE__ */ e.jsxs("div", { className: "flex justify-between gap-4 flex-1 items-center py-0.5 px-2.5", children: [
        /* @__PURE__ */ e.jsxs("div", { className: "flex flex-col gap-2 basis-1/2", children: [
          /* @__PURE__ */ e.jsx(S, { className: "font-medium", title: "Query", description: "Select a query" }),
          /* @__PURE__ */ e.jsxs(
            D,
            {
              "aria-required": !0,
              defaultValue: l?.queryId,
              size: "2",
              onValueChange: (a) => c(
                (t) => ({
                  ...t ?? {},
                  queryId: a,
                  params: g.find((s) => s.id === a)?.parameters?.map((s) => ({
                    field: s,
                    op: y(s)
                  })) ?? []
                })
              ),
              children: [
                /* @__PURE__ */ e.jsx(
                  R,
                  {
                    radius: "medium",
                    variant: "surface",
                    placeholder: "Select a query",
                    className: "!max-w-2/3 !mr-[1px]"
                  }
                ),
                /* @__PURE__ */ e.jsx(k, { children: /* @__PURE__ */ e.jsxs(M, { children: [
                  /* @__PURE__ */ e.jsx(ge, { children: "Available queries" }),
                  g.map((a) => /* @__PURE__ */ e.jsx(W, { value: a.id, children: a.label }, a.id))
                ] }) })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ e.jsxs("div", { className: "flex flex-col basis-1/2 gap-2", children: [
          /* @__PURE__ */ e.jsx(
            S,
            {
              withIcon: !0,
              className: "font-medium",
              title: "Alias",
              description: "Alias for the query results, used in dynamic content. Use a simple keyword without spaces or special characters. Aliases are unique across the page.",
              containerClassName: "!basis-0"
            }
          ),
          /* @__PURE__ */ e.jsx(
            O,
            {
              defaultValue: l?.alias,
              placeholder: "Ex: latestPosts",
              pattern: "^[a-zA-Z0-9_]+$",
              onChange: (a) => {
                c((t) => ({
                  ...t,
                  alias: a.target.value
                }));
              },
              className: "!w-full"
            }
          )
        ] })
      ] }),
      m.length > 0 && /* @__PURE__ */ e.jsxs("div", { className: "flex flex-col gap-2 flex-1 justify-between pt-3 px-2.5", children: [
        /* @__PURE__ */ e.jsx("div", { className: "flex flex-1 w-full justify-between items-center", children: /* @__PURE__ */ e.jsx(
          S,
          {
            title: "Parameters",
            className: "font-medium",
            description: "Specify parameters for this query"
          }
        ) }),
        m.length > 0 && /* @__PURE__ */ e.jsx("div", { className: "flex flex-col gap-3 mt-1", children: m.map((a, t) => /* @__PURE__ */ e.jsxs(X, { children: [
          /* @__PURE__ */ e.jsxs("div", { className: "flex gap-x-3 gap-y-0.5 items-center", children: [
            /* @__PURE__ */ e.jsx("div", { className: "w-[200px] flex items-center gap-3 pr-1", children: H(a) }),
            /* @__PURE__ */ e.jsx("div", { className: q("flex gap-2 items-center w-[120px]"), children: /* @__PURE__ */ e.jsxs(
              D,
              {
                defaultValue: y(a),
                size: "2",
                onValueChange: (s) => b(a, "op", s),
                children: [
                  /* @__PURE__ */ e.jsx(
                    R,
                    {
                      radius: "medium",
                      variant: "ghost",
                      placeholder: "Select operator",
                      className: "!flex-1 !mr-1"
                    }
                  ),
                  /* @__PURE__ */ e.jsx(k, { position: "popper", children: /* @__PURE__ */ e.jsx(M, { children: $(a).map((s) => /* @__PURE__ */ e.jsx(W, { value: s.value, children: s.label }, s.value)) }) })
                ]
              },
              `operator-${t}-${a}`
            ) }),
            p(a) === "date" || p(a) === "datetime" ? (y(a) === "before" || y(a) === "after" || y(a) === "eq") && // Absolute date: span both columns
            /* @__PURE__ */ e.jsx("div", { className: q("grow flex justify-end"), children: /* @__PURE__ */ e.jsx(
              O,
              {
                size: "2",
                type: p(a) === "datetime" ? "datetime-local" : "date",
                defaultValue: String(N(a)),
                onChange: (s) => b(a, "value", s.target.value),
                className: "!w-full"
              }
            ) }) : (
              // Non-date fields: span both columns
              /* @__PURE__ */ e.jsx("div", { className: q("grow flex justify-end"), children: p(a) === "number" || p(a) === "integer" ? /* @__PURE__ */ e.jsx(
                O,
                {
                  type: "number",
                  size: "2",
                  defaultValue: String(N(a)),
                  onChange: (s) => b(a, "value", Number(s.target.value)),
                  placeholder: "Value",
                  min: "1",
                  className: "!w-full"
                }
              ) : p(a) === "boolean" ? /* @__PURE__ */ e.jsxs(
                be,
                {
                  size: "1",
                  defaultValue: String(N(a) || "true"),
                  onValueChange: (s) => b(a, "value", s === "true"),
                  className: q("!mt-0.5 [&_.rt-SegmentedControlItemLabel]:(px-3)"),
                  children: [
                    /* @__PURE__ */ e.jsx(G, { value: "true", children: "True" }),
                    /* @__PURE__ */ e.jsx(G, { value: "false", children: "False" })
                  ]
                }
              ) : p(a) === "array" ? /* @__PURE__ */ e.jsx(
                de,
                {
                  initialValue: N(a, []),
                  onChange: (s) => b(a, "value", s),
                  className: "!w-full",
                  placeholder: "Add tags"
                }
              ) : (
                // <TextField.Root
                //   defaultValue={String(getFieldValue(param))}
                //   onChange={debounce((e) => updateParam(index, "value", e.target.value), 400)}
                //   placeholder="Value"
                //   size="2"
                //   className="!w-full max-w-full"
                // />
                /* @__PURE__ */ e.jsx(
                  ue,
                  {
                    isMulti: !1,
                    creatable: !0,
                    clearable: !0,
                    initialValue: N(a, []),
                    onChange: (s) => b(a, "value", s),
                    className: "!w-full",
                    placeholder: "Value or variable",
                    options: i.map((s) => ({
                      label: s,
                      value: s
                    }))
                  }
                )
              ) })
            )
          ] }),
          t < m.length - 1 && /* @__PURE__ */ e.jsx("div", { className: "border-t border-dotted mx-auto w-2/3 border-gray-200 my-2 relative", children: /* @__PURE__ */ e.jsx("span", { className: "absolute left-1/2 -translate-x-1/2 -top-3 bg-gray-50 rounded-full px-2 py-1 inline-block text-xs text-gray-500", children: "And" }) })
        ] }, t)) })
      ] })
    ] }),
    /* @__PURE__ */ e.jsxs("div", { className: "flex justify-end gap-2 mt-10", children: [
      h && /* @__PURE__ */ e.jsx(
        P,
        {
          type: "button",
          size: "2",
          color: "gray",
          variant: "soft",
          onClick: () => {
            x(), u?.();
          },
          children: "Cancel"
        }
      ),
      /* @__PURE__ */ e.jsx(P, { disabled: n() === !1, onClick: Y, size: "2", children: r ? "Save query" : "Add quer" })
    ] })
  ] });
}
export {
  He as default
};
//# sourceMappingURL=page-queries.js.map
