<template>
  <div class="flex flex-row gap-2 w-full">
    <div class="flex flex-row flex-wrap gap-2 items-center w-full">
      <div v-for="(condition, index) in value" class="contents">
        <NestedCondition
          v-if="condition.structureType == 'nested'"
          :model-value="condition"
          :table="table"
          @update:model-value="($event) => (value[index] = $event)"
          @remove="removeAtIndex(index)"
        />
        <Condition
          v-else
          :model-value="condition"
          :table="table"
          @update:model-value="($event) => (value[index] = $event)"
          @remove="removeAtIndex(index)"
        />
      </div>
      <div class="flex flex-row gap-2 items-center justify-end w-full">
        <div class="p-1 border border-gray-400 hover:bg-gray-200 rounded-md" @click="addConditionToValue">
          <PlusIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
        </div>
        <div class="p-1 border border-gray-400 hover:bg-gray-200 rounded-md" @click="addNestedToValue">
          <RectangleStackIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, type PropType } from "vue";
import { mapActions, mapState } from "pinia";
import type { ConditionStructure } from "@/types/dynamicQueries";
import { useQueryBuilderStore } from "@/stores/admin/club/queryBuilder";
import NestedCondition from "./NestedCondition.vue";
import Condition from "./Condition.vue";
import { PlusIcon, RectangleStackIcon } from "@heroicons/vue/24/outline";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    table: {
      type: String,
      default: "",
    },
    modelValue: {
      type: Array as PropType<Array<ConditionStructure>>,
      default: [],
    },
  },
  emits: ["update:model-value"],
  data() {
    return {};
  },
  computed: {
    ...mapState(useQueryBuilderStore, ["tableMetas"]),
    activeTable() {
      return this.tableMetas.find((tm) => tm.tableName == this.table);
    },
    value: {
      get() {
        return this.modelValue;
      },
      set(val: Array<ConditionStructure>) {
        this.$emit("update:model-value", val);
      },
    },
  },
  methods: {
    addNestedToValue() {
      this.value.push({
        structureType: "nested",
        concat: this.value.length == 0 ? "_" : "AND",
        conditions: [],
      });
    },
    addConditionToValue() {
      this.value.push({
        structureType: "condition",
        concat: this.value.length == 0 ? "_" : "AND",
        operation: "eq",
        column: "",
        value: "",
      });
    },
    removeAtIndex(index: number) {
      this.value.splice(index, 1);
    },
  },
});
</script>
