import { jsx } from 'react/jsx-runtime';
import { injectGlobal } from '@emotion/css';
import { useState, useMemo, useEffect, useCallback } from 'react';
import { Utils, Query, Builder } from '@react-awesome-query-builder/ui';
import '../types.js';
import { raqbConfig, emptyInitTree } from './AwesomeQueryBuilder.js';

function WhereRow({ sql, config, onSqlChange }) {
  const [tree, setTree] = useState();
  const configWithDefaults = useMemo(() => ({ ...raqbConfig, ...config }), [config]);
  useEffect(() => {
    var _a;
    if (!tree) {
      const initTree = Utils.checkTree(Utils.loadTree((_a = sql.whereJsonTree) != null ? _a : emptyInitTree), configWithDefaults);
      setTree(initTree);
    }
  }, [configWithDefaults, sql.whereJsonTree, tree]);
  useEffect(() => {
    if (!sql.whereJsonTree) {
      setTree(Utils.checkTree(Utils.loadTree(emptyInitTree), configWithDefaults));
    }
  }, [configWithDefaults, sql.whereJsonTree]);
  const onTreeChange = useCallback(
    (changedTree, config2) => {
      setTree(changedTree);
      const newSql = {
        ...sql,
        whereJsonTree: Utils.getTree(changedTree),
        whereString: Utils.sqlFormat(changedTree, config2)
      };
      onSqlChange(newSql);
    },
    [onSqlChange, sql]
  );
  if (!tree) {
    return null;
  }
  return /* @__PURE__ */ jsx(
    Query,
    {
      ...configWithDefaults,
      value: tree,
      onChange: onTreeChange,
      renderBuilder: (props) => /* @__PURE__ */ jsx(Builder, { ...props })
    }
  );
}
function flex(direction) {
  return `
    display: flex;
    gap: 8px;
    flex-direction: ${direction};`;
}
injectGlobal`
  .group--header {
    ${flex("row")}
  }

  .group-or-rule {
    ${flex("column")}
    .rule {
      flex-direction: row;
    }
  }

  .rule--body {
    ${flex("row")}
  }

  .group--children {
    ${flex("column")}
  }

  .group--conjunctions:empty {
    display: none;
  }
`;

export { WhereRow };
//# sourceMappingURL=WhereRow.js.map
