/* eslint-disable */
// ============================================================
// FILTER EDITOR — structured filter UI matching the spec
//   Filter: [
//     { PropertyName, LogicalOperator: "AND"|"OR",
//       Filters: [{ Operator, Value }] }
//   ]
// ============================================================

const { useState: useFE_S, useMemo: useFE_M } = React;

// Operators available per data type (spec-aligned)
const OPS_BY_TYPE = {
  string:   ["Contains","DoesNotContain","Eq","Neq","StartsWith","EndsWith","IsEmpty","IsNotEmpty"],
  enum:     ["Eq","Neq","IsEmpty","IsNotEmpty"],
  int:      ["Eq","Neq","IsGreaterThan","IsGreaterThanOrEqualTo","IsLessThan","IsLessThanOrEqualTo","IsEmpty","IsNotEmpty"],
  decimal:  ["Eq","Neq","IsGreaterThan","IsGreaterThanOrEqualTo","IsLessThan","IsLessThanOrEqualTo"],
  number:   ["Eq","Neq","IsGreaterThan","IsGreaterThanOrEqualTo","IsLessThan","IsLessThanOrEqualTo"],
  datetime: ["Eq","IsGreaterThan","IsGreaterThanOrEqualTo","IsLessThan","IsLessThanOrEqualTo"],
  bool:     ["Eq","Neq"],
};

const OP_LABELS = {
  Contains: "contains",
  DoesNotContain: "does not contain",
  Eq: "equals",
  Neq: "is not",
  StartsWith: "starts with",
  EndsWith: "ends with",
  IsEmpty: "is empty",
  IsNotEmpty: "is not empty",
  IsGreaterThan: ">",
  IsGreaterThanOrEqualTo: "≥",
  IsLessThan: "<",
  IsLessThanOrEqualTo: "≤",
};

const NO_VALUE_OPS = new Set(["IsEmpty", "IsNotEmpty"]);

const FilterRow = ({ col, group, onChange, onRemove, optionSets }) => {
  const ops = OPS_BY_TYPE[col.DataType] || OPS_BY_TYPE.string;
  const opts = col.OptionSet ? (optionSets[col.OptionSet] || []) : null;
  const filters = group.Filters || [];

  const setFilterAt = (idx, patch) => {
    const next = filters.map((f, i) => (i === idx ? { ...f, ...patch } : f));
    onChange({ ...group, Filters: next });
  };
  const removeAt = (idx) => onChange({ ...group, Filters: filters.filter((_, i) => i !== idx) });
  const add = () => onChange({ ...group, Filters: [...filters, { Operator: ops[0], Value: "" }] });

  return (
    <div className="card-flat p-2.5">
      <div className="flex items-center gap-2 mb-2">
        <div className="text-[12.5px] font-semibold flex-1" style={{ color: "var(--ink)" }}>
          {col.Label} <span className="text-[11px] font-normal" style={{ color: "var(--subtle)" }}>· {col.DataType}</span>
        </div>
        {filters.length > 1 && (
          <Select
            value={group.LogicalOperator || "AND"}
            onChange={(v) => onChange({ ...group, LogicalOperator: v })}
            options={[{ value: "AND", label: "All match" }, { value: "OR", label: "Any matches" }]}
            className="w-28"
          />
        )}
        <button onClick={onRemove} className="h-7 w-7 inline-flex items-center justify-center rounded hover:bg-[var(--surface-2)]" style={{ color: "var(--subtle)" }} title="Remove filter">
          <Icon name="x" size={14} />
        </button>
      </div>
      <div className="space-y-1.5">
        {filters.map((f, idx) => (
          <div key={idx} className="grid grid-cols-[140px_1fr_auto] items-center gap-2">
            <Select
              value={f.Operator}
              onChange={(v) => setFilterAt(idx, { Operator: v, Value: NO_VALUE_OPS.has(v) ? "" : f.Value })}
              options={ops.map((o) => ({ value: o, label: OP_LABELS[o] || o }))}
            />
            {NO_VALUE_OPS.has(f.Operator) ? (
              <div className="text-[12px] italic px-2.5" style={{ color: "var(--subtle)" }}>(no value)</div>
            ) : opts ? (
              <Select
                value={f.Value}
                onChange={(v) => setFilterAt(idx, { Value: v })}
                options={[{ value: "", label: "—" }, ...opts.map((o) => ({ value: o, label: o }))]}
              />
            ) : col.DataType === "int" || col.DataType === "decimal" || col.DataType === "number" ? (
              <NumberInput value={f.Value} onChange={(v) => setFilterAt(idx, { Value: v })} />
            ) : col.DataType === "datetime" ? (
              <input
                type="date"
                value={(f.Value || "").slice(0,10)}
                onChange={(e) => setFilterAt(idx, { Value: e.target.value ? `${e.target.value}T00:00:00Z` : "" })}
                className="w-full h-8 px-2.5 text-[13px] focus:outline-none focus:border-[var(--primary)]"
                style={{ background: "var(--surface)", color: "var(--ink)", border: "1px solid var(--border)", borderRadius: 7 }}
              />
            ) : (
              <TextInput value={f.Value} onChange={(v) => setFilterAt(idx, { Value: v })} placeholder="value" />
            )}
            <button onClick={() => removeAt(idx)} className="h-7 w-7 inline-flex items-center justify-center rounded hover:bg-[var(--surface-2)]" style={{ color: "var(--subtle)" }} disabled={filters.length === 1}>
              <Icon name="minus" size={14} />
            </button>
          </div>
        ))}
      </div>
      <button onClick={add} className="mt-2 inline-flex items-center gap-1 text-[12px] font-medium" style={{ color: "var(--primary)" }}>
        <Icon name="plus" size={12} /> add condition
      </button>
    </div>
  );
};

const FilterEditor = ({ open, onClose, columns, filter, onApply, optionSets }) => {
  const [draft, setDraft] = useFE_S(filter || []);
  React.useEffect(() => { if (open) setDraft(filter || []); }, [open, filter]);

  // Columns that are Filterable and Visible
  const filterableCols = useFE_M(
    () => columns.filter((c) => c.Filterable !== false),
    [columns]
  );

  const availableCols = filterableCols.filter((c) => !draft.find((d) => d.PropertyName === c.PropertyName));

  const addFor = (propertyName) => {
    const col = filterableCols.find((c) => c.PropertyName === propertyName);
    const ops = OPS_BY_TYPE[col.DataType] || OPS_BY_TYPE.string;
    setDraft([...draft, { PropertyName: propertyName, LogicalOperator: "AND", Filters: [{ Operator: ops[0], Value: "" }] }]);
  };

  const updateAt = (idx, next) => setDraft(draft.map((d, i) => (i === idx ? next : d)));
  const removeAt = (idx) => setDraft(draft.filter((_, i) => i !== idx));
  const clearAll = () => setDraft([]);

  return (
    <Modal
      open={open}
      title="Filter"
      subtitle="Filters are AND-ed across columns. Within a column, choose AND/OR for multiple conditions."
      onClose={onClose}
      size="lg"
      footer={
        <>
          <Btn variant="ghost" onClick={clearAll}>Clear all</Btn>
          <div className="flex-1" />
          <Btn variant="secondary" onClick={onClose}>Cancel</Btn>
          <Btn variant="primary" onClick={() => { onApply(draft); onClose(); }}>
            <Icon name="check" size={13} /> Apply filter
          </Btn>
        </>
      }
    >
      <div className="space-y-2 max-h-[55vh] overflow-y-auto scrollbar-thin pr-1">
        {draft.length === 0 && (
          <div className="text-center py-8">
            <div className="text-[13px]" style={{ color: "var(--muted)" }}>No filters yet</div>
            <div className="text-[12px] mt-1" style={{ color: "var(--subtle)" }}>Add a column below to start narrowing the list.</div>
          </div>
        )}
        {draft.map((group, idx) => {
          const col = filterableCols.find((c) => c.PropertyName === group.PropertyName);
          if (!col) return null;
          return (
            <FilterRow
              key={group.PropertyName}
              col={col}
              group={group}
              optionSets={optionSets}
              onChange={(g) => updateAt(idx, g)}
              onRemove={() => removeAt(idx)}
            />
          );
        })}
      </div>

      {availableCols.length > 0 && (
        <div className="mt-3 pt-3 border-t" style={{ borderColor: "var(--border)" }}>
          <div className="text-[11px] font-semibold uppercase tracking-wider mb-2" style={{ color: "var(--muted)" }}>Add filter on</div>
          <div className="flex flex-wrap gap-1.5">
            {availableCols.map((c) => (
              <button
                key={c.PropertyName}
                onClick={() => addFor(c.PropertyName)}
                className="inline-flex items-center gap-1 h-7 px-2.5 rounded-md text-[12px] font-medium"
                style={{ background: "var(--surface-3)", color: "var(--ink-2)" }}
              >
                <Icon name="plus" size={11} style={{ color: "var(--subtle)" }} /> {c.Label}
              </button>
            ))}
          </div>
        </div>
      )}
    </Modal>
  );
};

// Tiny inline pill showing active filter count + a button to open the editor
const FilterPill = ({ filter, onClick, onClear }) => {
  const n = (filter || []).length;
  if (n === 0) {
    return (
      <Btn variant="secondary" onClick={onClick}>
        <Icon name="filter" size={13} /> <span className="hidden sm:inline">Filter</span>
      </Btn>
    );
  }
  return (
    <span className="inline-flex items-center gap-1 h-8 pl-2 pr-1 rounded-md text-[12px] font-medium pop">
      <Icon name="filter" size={12} />
      <button onClick={onClick}>{n} filter{n === 1 ? "" : "s"}</button>
      <button onClick={onClear} className="ml-0.5 h-6 w-6 inline-flex items-center justify-center rounded hover:bg-[var(--primary-bg)]" title="Clear filters">
        <Icon name="x" size={11} />
      </button>
    </span>
  );
};

Object.assign(window, { FilterEditor, FilterPill, OPS_BY_TYPE, OP_LABELS });
