"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { ChevronDown, Plus, Trash2, X } from "lucide-react";
import { Button } from "../../primitives/button.js";
import { IconButton } from "../../primitives/icon-button.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  OPERATORS_BY_FIELD_TYPE,
  getDefaultOperator,
  isValuelessOperator,
  createEmptyCondition,
  normalizeAdvancedFilterState
} from "@open-mercato/shared/lib/query/advanced-filter";
const OPERATOR_LABELS = {
  is: "is",
  is_not: "is not",
  contains: "contains",
  does_not_contain: "does not contain",
  starts_with: "starts with",
  ends_with: "ends with",
  is_empty: "is empty",
  is_not_empty: "is not empty",
  equals: "equals",
  not_equals: "not equals",
  greater_than: "greater than",
  less_than: "less than",
  greater_or_equal: "greater or equal",
  less_or_equal: "less or equal",
  between: "between",
  is_before: "is before",
  is_after: "is after",
  is_any_of: "is any of",
  is_none_of: "is none of",
  is_true: "is true",
  is_false: "is false",
  has_any_of: "has any of",
  has_all_of: "has all of",
  has_none_of: "has none of"
};
function getFieldType(fields, fieldKey) {
  const field = fields.find((f) => f.key === fieldKey);
  return field?.type ?? "text";
}
function ConditionRow({
  condition,
  index,
  fields,
  join,
  onUpdate,
  onRemove,
  onToggleJoin,
  t
}) {
  const fieldType = getFieldType(fields, condition.field);
  const operators = OPERATORS_BY_FIELD_TYPE[fieldType] ?? OPERATORS_BY_FIELD_TYPE.text;
  const valueless = isValuelessOperator(condition.operator);
  const handleFieldChange = (newField) => {
    const newType = getFieldType(fields, newField);
    const newOp = getDefaultOperator(newType);
    onUpdate(condition.id, { field: newField, operator: newOp, value: "" });
  };
  const joinLabel = join === "and" ? t("ui.advancedFilter.and", "And") : t("ui.advancedFilter.or", "Or");
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start gap-2", children: [
    /* @__PURE__ */ jsx("div", { className: "w-20 shrink-0 pt-0.5 text-sm text-muted-foreground", children: index === 0 ? /* @__PURE__ */ jsx("span", { children: t("ui.advancedFilter.where", "Where") }) : /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        variant: "outline",
        size: "sm",
        className: "h-9 min-w-[5rem] justify-between px-3 text-sm font-medium",
        onClick: () => onToggleJoin(condition.id),
        "aria-label": t("ui.advancedFilter.toggleJoin", "Toggle filter join operator"),
        title: t("ui.advancedFilter.toggleJoinHint", "Click to switch between AND and OR"),
        children: [
          /* @__PURE__ */ jsx("span", { children: joinLabel }),
          /* @__PURE__ */ jsx(ChevronDown, { className: "size-3.5 text-muted-foreground" })
        ]
      }
    ) }),
    /* @__PURE__ */ jsxs(
      "select",
      {
        className: "rounded border bg-background px-2 py-1.5 text-sm min-w-[140px]",
        value: condition.field,
        onChange: (e) => handleFieldChange(e.target.value),
        "aria-label": t("ui.advancedFilter.selectField", "Select field"),
        children: [
          /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: t("ui.advancedFilter.selectFieldPlaceholder", "Select field...") }),
          fields.map((f) => /* @__PURE__ */ jsx("option", { value: f.key, children: f.label }, f.key))
        ]
      }
    ),
    /* @__PURE__ */ jsx(
      "select",
      {
        className: "rounded border bg-background px-2 py-1.5 text-sm min-w-[120px]",
        value: condition.operator,
        onChange: (e) => onUpdate(condition.id, { operator: e.target.value, value: "" }),
        "aria-label": t("ui.advancedFilter.selectOperator", "Select operator"),
        children: operators.map((op) => /* @__PURE__ */ jsx("option", { value: op, children: t(`ui.advancedFilter.operator.${op}`, OPERATOR_LABELS[op]) }, op))
      }
    ),
    !valueless ? /* @__PURE__ */ jsx(
      ValueInput,
      {
        condition,
        fields,
        fieldType,
        onUpdate,
        t
      }
    ) : null,
    /* @__PURE__ */ jsx(
      IconButton,
      {
        variant: "ghost",
        size: "sm",
        type: "button",
        onClick: () => onRemove(condition.id),
        "aria-label": t("ui.advancedFilter.removeCondition", "Remove condition"),
        children: /* @__PURE__ */ jsx(Trash2, { className: "size-4 text-muted-foreground" })
      }
    )
  ] });
}
function ValueInput({
  condition,
  fields,
  fieldType,
  onUpdate,
  t
}) {
  const fieldDef = fields.find((f) => f.key === condition.field);
  const value = condition.value;
  if (fieldType === "select" && fieldDef?.options) {
    return /* @__PURE__ */ jsxs(
      "select",
      {
        className: "rounded border bg-background px-2 py-1.5 text-sm min-w-[140px]",
        value: typeof value === "string" ? value : "",
        onChange: (e) => onUpdate(condition.id, { value: e.target.value }),
        "aria-label": t("ui.advancedFilter.selectValue", "Select value"),
        children: [
          /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: t("ui.advancedFilter.selectValuePlaceholder", "Select...") }),
          fieldDef.options.map((opt) => /* @__PURE__ */ jsx("option", { value: opt.value, children: opt.label }, opt.value))
        ]
      }
    );
  }
  if (fieldType === "date") {
    return /* @__PURE__ */ jsx(
      "input",
      {
        type: "date",
        className: "rounded border bg-background px-2 py-1.5 text-sm",
        value: typeof value === "string" ? value : "",
        onChange: (e) => onUpdate(condition.id, { value: e.target.value }),
        "aria-label": t("ui.advancedFilter.dateValue", "Date value")
      }
    );
  }
  if (fieldType === "number") {
    return /* @__PURE__ */ jsx(
      "input",
      {
        type: "number",
        className: "rounded border bg-background px-2 py-1.5 text-sm w-[120px]",
        value: typeof value === "number" ? value : typeof value === "string" ? value : "",
        onChange: (e) => onUpdate(condition.id, { value: e.target.value }),
        placeholder: t("ui.advancedFilter.numberPlaceholder", "Value"),
        "aria-label": t("ui.advancedFilter.numberValue", "Number value")
      }
    );
  }
  return /* @__PURE__ */ jsx(
    "input",
    {
      type: "text",
      className: "rounded border bg-background px-2 py-1.5 text-sm min-w-[140px]",
      value: typeof value === "string" ? value : "",
      onChange: (e) => onUpdate(condition.id, { value: e.target.value }),
      placeholder: t("ui.advancedFilter.textPlaceholder", "Value..."),
      "aria-label": t("ui.advancedFilter.textValue", "Text value")
    }
  );
}
function AdvancedFilterBuilder({
  fields,
  value,
  onChange,
  onApply,
  onClear
}) {
  const t = useT();
  const normalizedValue = React.useMemo(() => normalizeAdvancedFilterState(value), [value]);
  const emitChange = React.useCallback((next) => {
    onChange(normalizeAdvancedFilterState(next));
  }, [onChange]);
  const updateCondition = React.useCallback((id, updates) => {
    emitChange({
      ...normalizedValue,
      conditions: normalizedValue.conditions.map((c) => c.id === id ? { ...c, ...updates } : c)
    });
  }, [emitChange, normalizedValue]);
  const removeCondition = React.useCallback((id) => {
    emitChange({
      ...normalizedValue,
      conditions: normalizedValue.conditions.filter((c) => c.id !== id)
    });
  }, [emitChange, normalizedValue]);
  const addCondition = React.useCallback(() => {
    const newCondition = createEmptyCondition();
    if (fields.length > 0) {
      newCondition.field = fields[0].key;
      newCondition.operator = getDefaultOperator(fields[0].type);
    }
    emitChange({
      ...normalizedValue,
      conditions: [...normalizedValue.conditions, newCondition]
    });
  }, [emitChange, fields, normalizedValue]);
  const toggleConditionJoin = React.useCallback((id) => {
    emitChange({
      ...normalizedValue,
      conditions: normalizedValue.conditions.map((condition) => condition.id === id ? { ...condition, join: condition.join === "or" ? "and" : "or" } : condition)
    });
  }, [emitChange, normalizedValue]);
  return /* @__PURE__ */ jsxs("div", { className: "inline-flex flex-col gap-3 p-3", children: [
    normalizedValue.conditions.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("ui.advancedFilter.noConditions", 'No filter conditions. Click "Add filter" to start.') }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: normalizedValue.conditions.map((condition, index) => /* @__PURE__ */ jsx(
      ConditionRow,
      {
        condition,
        index,
        fields,
        join: condition.join ?? normalizedValue.logic,
        onUpdate: updateCondition,
        onRemove: removeCondition,
        onToggleJoin: toggleConditionJoin,
        t
      },
      condition.id
    )) }),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3 pt-2", children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          className: "h-auto px-0 py-0 text-base font-medium text-primary hover:bg-transparent hover:text-primary/90",
          onClick: addCondition,
          children: [
            /* @__PURE__ */ jsx(Plus, { className: "size-4" }),
            t("ui.advancedFilter.addFilter", "Add filter")
          ]
        }
      ),
      normalizedValue.conditions.length > 0 ? /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          className: "h-auto px-0 py-0 text-base text-muted-foreground hover:bg-transparent hover:text-foreground",
          onClick: onClear,
          children: [
            /* @__PURE__ */ jsx(X, { className: "size-4" }),
            t("ui.advancedFilter.clear", "Clear")
          ]
        }
      ) : null,
      normalizedValue.conditions.length > 0 ? /* @__PURE__ */ jsx(Button, { type: "button", className: "ml-auto min-w-[8rem]", onClick: onApply, children: t("ui.advancedFilter.apply", "Apply") }) : null
    ] })
  ] });
}
export {
  AdvancedFilterBuilder
};
//# sourceMappingURL=AdvancedFilterBuilder.js.map
