<template>
  <div class="flex flex-row gap-2">
    <p class="w-14 min-w-14 pt-2">JOIN</p>
    <div class="flex flex-row flex-wrap gap-2 items-center w-full">
      <div class="flex flex-row flex-wrap gap-2 items-center justify-end w-full">
        <JoinTable
          v-for="(join, index) in value"
          :model-value="join"
          :table="table"
          :alreadyJoined="alreadyJoined"
          @update:model-value="($event) => (value[index] = $event)"
          @remove="removeAtIndex(index)"
        />
        <div class="p-1 border border-gray-400 hover:bg-gray-200 rounded-md" @click="addToValue">
          <PlusIcon 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 DynamicQueryStructure } from "@/types/dynamicQueries";
import { useQueryBuilderStore } from "@/stores/admin/club/queryBuilder";
import { PlusIcon } from "@heroicons/vue/24/outline";
import JoinTable from "./JoinTable.vue";
import { v4 as uuid } from "uuid";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    table: {
      type: String,
      default: "",
    },
    modelValue: {
      type: Array as PropType<Array<DynamicQueryStructure & { foreignColumn: string }>>,
      default: [],
    },
    alreadyJoined: {
      type: Array as PropType<Array<string>>,
      default: [],
    },
  },
  emits: ["update:model-value"],
  computed: {
    ...mapState(useQueryBuilderStore, ["tableMetas"]),
    value: {
      get() {
        return this.modelValue;
      },
      set(val: Array<DynamicQueryStructure & { foreignColumn: string }>) {
        this.$emit("update:model-value", val);
      },
    },
  },
  methods: {
    addToValue() {
      this.value.push({
        id: uuid(),
        select: "*",
        table: "",
        where: [],
        join: [],
        orderBy: [],
        foreignColumn: "",
      });
    },
    removeAtIndex(index: number) {
      this.value.splice(index, 1);
    },
  },
});
</script>
