"use client";
import { jsxs as f, jsx as o, Fragment as T } from "react/jsx-runtime";
import { useState as P } from "react";
import { AppSelect as C } from "../../../app-select.js";
import { Button as h } from "../../../button.js";
import { Popover as A, PopoverTrigger as G, PopoverContent as S } from "../../../popover.js";
import { errorSelectClass as D, getListMultiSelectFilterOptions as k, getListSingleSelectFilterOptions as V, getDateTimeFilterOptions as K, getDateFilterOptions as q, getBooleanFilterOptions as B, getNumberFilterOptions as E, getStringFilterOptions as M } from "../data-table-constants.js";
import { FilterValueInput as $ } from "./data-table-filter-inputs.js";
import { cn as H } from "../../../../../lib/utils.js";
function m() {
  return Math.random().toString(36).substr(2, 9);
}
function R({
  onDelete: s,
  onDuplicate: e,
  type: u,
  i18n: i
}) {
  return /* @__PURE__ */ f(A, { children: [
    /* @__PURE__ */ o(G, { asChild: !0, children: /* @__PURE__ */ o(
      h,
      {
        variant: "ghost",
        iconLeft: "Ellipsis",
        size: "sm",
        className: "size-7"
      }
    ) }),
    /* @__PURE__ */ f(S, { side: "right", className: "flex w-auto flex-col p-1", children: [
      /* @__PURE__ */ o(
        h,
        {
          className: "justify-start text-xs",
          variant: "ghost-destructive",
          iconLeft: "Trash2",
          size: "sm",
          onClick: s,
          children: u === "condition" ? i.filters.deleteCondition : i.filters.deleteGroup
        }
      ),
      /* @__PURE__ */ o(
        h,
        {
          className: "justify-start text-xs",
          variant: "ghost",
          iconLeft: "Copy",
          size: "sm",
          onClick: e,
          children: u === "condition" ? i.filters.duplicateCondition : i.filters.duplicateGroup
        }
      )
    ] })
  ] });
}
function z(s, e) {
  switch (s) {
    case "string":
      return M(e);
    case "number":
      return E(e);
    case "boolean":
      return B(e);
    case "date":
      return q(e);
    case "datetime":
      return K(e);
    case "list_single_select":
      return V(e);
    case "list_multi_select":
      return k(e);
    default:
      return [];
  }
}
function J({
  condition: s,
  columns: e,
  onUpdate: u,
  onRemove: i,
  onDuplicate: w,
  showLogicalOperator: x = !1,
  logicalOperator: p = "AND",
  onLogicalOperatorChange: a,
  isFirstInGroup: g = !1,
  isSecondInGroup: y = !1,
  i18n: c
}) {
  const v = e.find((r) => r.id === s.columnId), O = v ? z(
    v.column.columnDef.meta?.type,
    c
  ) : [], b = () => {
    if (!v) return null;
    const r = v.column.columnDef.meta?.type, d = s.value === void 0 || typeof s.value == "string" && s.value === "" || r === "list_multi_select" && !Array.isArray(s.value);
    return /* @__PURE__ */ o(
      $,
      {
        columnType: r,
        value: s.value,
        onChange: (N) => u({ ...s, value: N }),
        listOptions: v.column.columnDef.meta?.listOptions ?? [],
        placeholder: c.filters.value,
        operator: s.operator,
        size: "sm",
        className: r === "list_single_select" || r === "list_multi_select" ? "w-52" : "",
        hasError: d
      }
    );
  };
  return /* @__PURE__ */ f("div", { className: "flex min-w-0 flex-1 items-center gap-2 rounded-md", children: [
    /* @__PURE__ */ f("div", { className: "flex min-w-0 flex-1 items-center gap-2 overflow-x-auto overflow-y-clip", children: [
      x && a && /* @__PURE__ */ o(T, { children: y ? /* @__PURE__ */ o(
        C,
        {
          size: "sm",
          className: `w-[72px] min-w-[72px] ${p === void 0 ? D : ""}`,
          options: [
            { value: "AND", label: c.filters.and },
            { value: "OR", label: c.filters.or }
          ],
          value: p,
          onValueChange: (r) => a(r)
        }
      ) : /* @__PURE__ */ o("span", { className: "text-muted-foreground w-[72px] min-w-[72px] text-right text-xs", children: p }) }),
      g && /* @__PURE__ */ o("span", { className: "text-muted-foreground w-[72px] min-w-[72px] text-right text-xs", children: c.filters.where }),
      /* @__PURE__ */ o(
        C,
        {
          size: "sm",
          placeholder: c.filters.column,
          className: s.columnId === void 0 || s.columnId === "" ? D : "",
          options: e.map((r) => ({
            value: r.id,
            label: r.column.columnDef.meta?.headerLabel || (typeof r.column.columnDef.header == "string" ? r.column.columnDef.header : "") || r.id
          })),
          value: s.columnId || void 0,
          onValueChange: (r) => {
            if (r) {
              const d = e.find((N) => N.id === r);
              if (d) {
                const N = z(
                  d.column.columnDef.meta?.type,
                  c
                )[0]?.value;
                u({
                  ...s,
                  columnId: String(r),
                  columnAccessorKey: (
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    (d.column.columnDef?.accessorKey ?? String(r)) || ""
                  ),
                  columnLabel: d.column.columnDef.meta?.headerLabel || (typeof d.column.columnDef.header == "string" ? d.column.columnDef.header : "") || d.id,
                  columnType: d.column.columnDef.meta?.type,
                  operator: String(N || "eq"),
                  value: void 0
                });
              }
            }
          }
        }
      ),
      s.columnId && /* @__PURE__ */ o(
        C,
        {
          size: "sm",
          placeholder: c.filters.operator,
          className: s.operator === void 0 ? D : "",
          options: O,
          value: s.operator || void 0,
          onValueChange: (r) => {
            r && u({
              ...s,
              operator: String(r)
            });
          }
        }
      ),
      b()
    ] }),
    /* @__PURE__ */ o(
      R,
      {
        type: "condition",
        onDelete: i,
        onDuplicate: w,
        i18n: c
      }
    )
  ] });
}
function _({
  className: s,
  group: e,
  columns: u,
  onUpdate: i,
  isRoot: w = !1,
  depth: x,
  maxNestedDepth: p = 2,
  i18n: a
}) {
  const g = {
    id: m(),
    columnId: "",
    columnAccessorKey: "",
    columnLabel: "",
    columnType: "string",
    operator: "eq",
    value: void 0
  }, y = {
    id: m(),
    logicalOperator: "AND",
    conditions: [
      {
        id: m(),
        columnId: "",
        columnAccessorKey: "",
        columnLabel: "",
        columnType: "string",
        operator: "eq",
        value: void 0
      }
    ],
    groups: []
  }, c = () => {
    i({
      ...e,
      conditions: [...e.conditions, g]
    });
  }, v = () => {
    i({
      ...e,
      groups: [...e.groups || [], y]
    });
  }, O = (l, t) => {
    i({
      ...e,
      conditions: e.conditions.map(
        (n) => n.id === l ? t : n
      )
    });
  }, b = (l) => {
    const t = e.conditions.findIndex((I) => I.id === l);
    if (t === -1) return;
    const F = {
      ...e.conditions[t],
      id: m()
    };
    i({
      ...e,
      conditions: [
        ...e.conditions.slice(0, t + 1),
        F,
        ...e.conditions.slice(t + 1)
      ]
    });
  }, r = (l) => {
    i({
      ...e,
      conditions: e.conditions.filter((t) => t.id !== l)
    });
  }, d = (l, t) => {
    i({
      ...e,
      groups: (e.groups || []).map(
        (n) => n.id === l ? t : n
      )
    });
  }, N = (l) => {
    i({
      ...e,
      groups: (e.groups || []).filter((t) => t.id !== l)
    });
  }, L = (l) => ({
    id: m(),
    logicalOperator: l.logicalOperator,
    conditions: l.conditions.map((t) => ({
      ...t,
      id: m()
    })),
    groups: (l.groups || []).map((t) => L(t))
  }), j = (l) => {
    const t = e.groups || [], n = t.findIndex((I) => I.id === l);
    if (n === -1) return;
    const F = L(t[n]);
    i({
      ...e,
      groups: [...t.slice(0, n + 1), F, ...t.slice(n + 1)]
    });
  };
  return /* @__PURE__ */ f(
    "div",
    {
      className: H(
        "min-w-0 space-y-2 overflow-auto",
        w ? "" : "bg-d-foreground/5 border-d-foreground rounded border-l-2 p-2 pl-3",
        s
      ),
      children: [
        e.conditions.map((l, t) => /* @__PURE__ */ o(
          J,
          {
            condition: l,
            columns: u,
            onUpdate: (n) => O(l.id, n),
            onRemove: () => r(l.id),
            onDuplicate: () => b(l.id),
            showLogicalOperator: t > 0,
            logicalOperator: e.logicalOperator,
            onLogicalOperatorChange: (n) => i({ ...e, logicalOperator: n }),
            isFirstInGroup: t === 0,
            isSecondInGroup: t === 1,
            i18n: a
          },
          l.id
        )),
        (e.groups || []).map((l, t) => /* @__PURE__ */ f(
          "div",
          {
            className: "flex min-w-0 flex-1 flex-row gap-2",
            children: [
              t === 1 && e.conditions.length === 0 || t === 0 && e.conditions.length === 1 ? /* @__PURE__ */ o(
                C,
                {
                  className: `w-[72px] min-w-[72px] ${e.logicalOperator === void 0 ? D : ""}`,
                  size: "sm",
                  options: [
                    { value: "AND", label: a.filters.and },
                    { value: "OR", label: a.filters.or }
                  ],
                  value: e.logicalOperator,
                  onValueChange: (n) => i({
                    ...e,
                    logicalOperator: n
                  })
                }
              ) : t === 0 && e.conditions.length === 0 ? /* @__PURE__ */ o("span", { className: "text-muted-foreground w-[72px] text-right text-xs", children: a.filters.where }) : /* @__PURE__ */ o("span", { className: "text-muted-foreground w-[72px] text-right text-xs", children: e.logicalOperator }),
              /* @__PURE__ */ o(
                _,
                {
                  className: "flex flex-1 flex-col",
                  group: l,
                  columns: u,
                  onUpdate: (n) => d(l.id, n),
                  depth: x + 1,
                  maxNestedDepth: p,
                  i18n: a
                }
              ),
              /* @__PURE__ */ o(
                R,
                {
                  type: "group",
                  onDelete: () => N(l.id),
                  onDuplicate: () => j(l.id),
                  i18n: a
                }
              )
            ]
          },
          l.id
        )),
        x < p ? /* @__PURE__ */ f(A, { children: [
          /* @__PURE__ */ o(G, { asChild: !0, children: /* @__PURE__ */ o(
            h,
            {
              variant: "ghost",
              size: "sm",
              className: "w-full justify-start text-xs",
              iconLeft: "Plus",
              iconRight: "ChevronDown",
              children: a.filters.addFilterRule
            }
          ) }),
          /* @__PURE__ */ f(S, { side: "top", className: "flex w-auto flex-col p-1", children: [
            /* @__PURE__ */ o(
              h,
              {
                variant: "ghost",
                size: "sm",
                className: "justify-start text-xs",
                iconLeft: "Plus",
                onClick: c,
                children: a.filters.addFilterRule
              }
            ),
            /* @__PURE__ */ o(
              h,
              {
                variant: "ghost",
                size: "sm",
                className: "justify-start text-xs",
                iconLeft: "CopyPlus",
                onClick: v,
                children: a.filters.addFilterGroup
              }
            )
          ] })
        ] }) : /* @__PURE__ */ o(
          h,
          {
            variant: "ghost",
            size: "sm",
            className: "w-full justify-start text-xs",
            iconLeft: "Plus",
            onClick: c,
            children: a.filters.addFilterRule
          }
        )
      ]
    }
  );
}
function le({
  columns: s,
  onFilterChange: e,
  initialFilter: u,
  i18n: i
}) {
  const [w, x] = P(
    u || {
      id: m(),
      rootGroup: {
        id: m(),
        logicalOperator: "AND",
        conditions: [],
        groups: []
      }
    }
  ), p = (g) => {
    const y = {
      ...w,
      rootGroup: g
    };
    x(y), e(y);
  }, a = () => {
    const g = {
      id: m(),
      rootGroup: {
        id: m(),
        logicalOperator: "AND",
        conditions: [],
        groups: []
      }
    };
    x(g), e(null);
  };
  return /* @__PURE__ */ f("div", { className: "flex max-h-[500px] min-w-0 flex-col gap-0.5 overflow-auto", children: [
    /* @__PURE__ */ o(
      _,
      {
        className: "flex flex-1 flex-col",
        group: w.rootGroup,
        columns: s,
        onUpdate: p,
        isRoot: !0,
        depth: 0,
        maxNestedDepth: 2,
        i18n: i
      }
    ),
    /* @__PURE__ */ o("div", { className: "border-d-border w-full border-b" }),
    /* @__PURE__ */ o(
      h,
      {
        variant: "ghost-destructive",
        size: "sm",
        onClick: a,
        className: "w-full justify-start text-xs",
        iconRight: "Trash2",
        children: i.filters.deleteFilter
      }
    )
  ] });
}
export {
  le as DataTableAdvancedFilterComponent
};
