import type { FilterGroup, Filter, TrackerField } from "../../lib/types";

const OPERATORS = ["In", "NotIn", "Equals", "NotEquals"] as const;

interface Props {
  groups: FilterGroup[];
  onChange: (groups: FilterGroup[]) => void;
  availableFields: TrackerField[];
}

export default function FilterBuilder({ groups, onChange, availableFields }: Props) {
  function updateGroup(groupIndex: number, group: FilterGroup) {
    const next = groups.map((g, i) => (i === groupIndex ? group : g));
    onChange(next);
  }

  function removeGroup(groupIndex: number) {
    onChange(groups.filter((_, i) => i !== groupIndex));
  }

  function addGroup() {
    onChange([...groups, { conditions: [{ field: "", operator: "In", value: [] }] }]);
  }

  function updateCondition(groupIndex: number, condIndex: number, cond: Filter) {
    const group = groups[groupIndex];
    const conditions = group.conditions.map((c, i) => (i === condIndex ? cond : c));
    updateGroup(groupIndex, { conditions });
  }

  function removeCondition(groupIndex: number, condIndex: number) {
    const group = groups[groupIndex];
    const conditions = group.conditions.filter((_, i) => i !== condIndex);
    updateGroup(groupIndex, { conditions });
  }

  function addCondition(groupIndex: number) {
    const group = groups[groupIndex];
    updateGroup(groupIndex, {
      conditions: [...group.conditions, { field: "", operator: "In", value: [] }],
    });
  }

  function toggleValue(groupIndex: number, condIndex: number, val: string) {
    const cond = groups[groupIndex].conditions[condIndex];
    const next = cond.value.includes(val)
      ? cond.value.filter((v) => v !== val)
      : [...cond.value, val];
    updateCondition(groupIndex, condIndex, { ...cond, value: next });
  }

  return (
    <div className="space-y-3">
      {groups.map((group, gi) => (
        <div key={gi}>
          {gi > 0 && (
            <div className="flex items-center gap-2 my-2">
              <div className="flex-1 border-t border-gray-200" />
              <span className="text-xs font-semibold text-gray-500 uppercase tracking-wide">AND</span>
              <div className="flex-1 border-t border-gray-200" />
            </div>
          )}
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="flex items-center justify-between mb-3">
              <span className="text-sm font-medium text-gray-700">Group {gi + 1}</span>
              <button
                type="button"
                onClick={() => removeGroup(gi)}
                className="text-xs text-red-500 hover:text-red-700"
              >
                Remove group
              </button>
            </div>

            <div className="space-y-3">
              {group.conditions.map((cond, ci) => {
                const fieldDef = availableFields.find((f) => f.label === cond.field);
                return (
                  <div key={ci}>
                    {ci > 0 && (
                      <div className="flex items-center gap-2 my-2">
                        <div className="flex-1 border-t border-dashed border-gray-200" />
                        <span className="text-xs font-semibold text-blue-400 uppercase tracking-wide">OR</span>
                        <div className="flex-1 border-t border-dashed border-gray-200" />
                      </div>
                    )}
                    <div className="space-y-2">
                      <div className="flex items-center gap-2">
                        {/* Field dropdown */}
                        <select
                          value={cond.field}
                          onChange={(e) =>
                            updateCondition(gi, ci, {
                              ...cond,
                              field: e.target.value,
                              value: [],
                            })
                          }
                          className="border border-gray-300 rounded px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 flex-1"
                        >
                          <option value="">Select field...</option>
                          {availableFields.map((f) => (
                            <option key={f.field_id} value={f.label}>
                              {f.label}
                            </option>
                          ))}
                        </select>

                        {/* Operator dropdown */}
                        <select
                          value={cond.operator}
                          onChange={(e) =>
                            updateCondition(gi, ci, { ...cond, operator: e.target.value })
                          }
                          className="border border-gray-300 rounded px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                        >
                          {OPERATORS.map((op) => (
                            <option key={op} value={op}>
                              {op}
                            </option>
                          ))}
                        </select>

                        {/* Remove condition */}
                        <button
                          type="button"
                          onClick={() => removeCondition(gi, ci)}
                          className="text-xs text-red-400 hover:text-red-600 whitespace-nowrap"
                        >
                          Remove
                        </button>
                      </div>

                      {/* Value pills */}
                      {fieldDef && fieldDef.values.length > 0 && (
                        <div className="flex flex-wrap gap-1 pl-1">
                          {fieldDef.values.map((v) => {
                            const selected = cond.value.includes(String(v.id));
                            return (
                              <button
                                key={v.id}
                                type="button"
                                onClick={() => toggleValue(gi, ci, String(v.id))}
                                className={`px-2 py-0.5 rounded-full text-xs border transition-colors ${
                                  selected
                                    ? "bg-blue-600 text-white border-blue-600"
                                    : "bg-white text-gray-700 border-gray-300 hover:border-blue-400"
                                }`}
                              >
                                {v.label}
                              </button>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>

            <button
              type="button"
              onClick={() => addCondition(gi)}
              className="mt-3 text-xs text-blue-600 hover:text-blue-800"
            >
              + Add OR condition
            </button>
          </div>
        </div>
      ))}

      <button
        type="button"
        onClick={addGroup}
        className="w-full px-4 py-2 border-2 border-dashed border-gray-300 rounded text-sm text-gray-500 hover:border-blue-400 hover:text-blue-600 transition-colors"
      >
        + Add filter group (AND)
      </button>
    </div>
  );
}
