<template>
  <div class="flex flex-row gap-2 w-full">
    <div class="flex flex-row gap-2 w-full">
      <div class="flex flex-col gap-2 w-full">
        <div class="flex flex-row gap-2 w-full">
          <div
            v-if="false"
            class="h-fit p-1 border border-gray-400 hover:bg-gray-200 rounded-md"
            title="Join Modus wechseln"
            @click="swapJoinType(value.type)"
          >
            <ArrowsUpDownIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
          </div>

          <select v-if="value.type == 'defined'" v-model="context" class="w-full">
            <option value="" disabled>Relation auswählen</option>
            <option
              v-for="relation in activeTable?.relations"
              :value="relation.column"
              :disabled="
                alreadyJoined.includes(joinTableName(relation.referencedTableName)) &&
                joinTableName(relation.referencedTableName) != value.table
              "
            >
              {{ relation.column }} -> {{ joinTableName(relation.referencedTableName) }}
              <span
                v-if="
                  alreadyJoined.includes(joinTableName(relation.referencedTableName)) &&
                  joinTableName(relation.referencedTableName) != value.table
                "
              >
                (Join auf dieser Ebene besteht schon)
              </span>
            </option>
          </select>
          <div v-else class="flex flex-col w-full">
            <select v-model="joinTable">
              <option value="" disabled>Tabelle auswählen</option>
              <option
                v-for="table in tableMetas"
                :value="table.tableName"
                :disabled="alreadyJoined.includes(table.tableName) && table.tableName != value.table"
              >
                {{ table.tableName }}
              </option>
            </select>
            <input v-model="context" type="text" placeholder="Join Condition tabA.col = tabB.col" />
          </div>
        </div>
        <Table v-model="value" disable-table-select :show-table-select="false" />
      </div>
      <div class="h-fit p-1 border border-gray-400 hover:bg-gray-200 rounded-md" @click="$emit('remove')">
        <TrashIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, type PropType } from "vue";
import { mapActions, mapState } from "pinia";
import { type DynamicQueryStructure, type JoinStructure } from "@/types/dynamicQueries";
import { useQueryBuilderStore } from "@/stores/admin/club/queryBuilder";
import Table from "./Table.vue";
import { ArrowsUpDownIcon, TrashIcon } from "@heroicons/vue/24/outline";
import { joinTableName } from "@/helpers/queryFormatter";
import { v4 as uuid } from "uuid";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    table: {
      type: String,
      default: "",
    },
    modelValue: {
      type: Object as PropType<DynamicQueryStructure & JoinStructure>,
      required: true,
    },
    alreadyJoined: {
      type: Array as PropType<Array<string>>,
      default: [],
    },
  },
  emits: ["update:model-value", "remove"],
  computed: {
    ...mapState(useQueryBuilderStore, ["tableMetas"]),
    activeTable() {
      return this.tableMetas.find((tm) => tm.tableName == this.table);
    },
    value: {
      get() {
        return this.modelValue;
      },
      set(val: DynamicQueryStructure & JoinStructure) {
        this.$emit("update:model-value", val);
      },
    },
    context: {
      get() {
        if (this.modelValue.type == "defined") {
          return this.modelValue.foreignColumn ?? "";
        } else {
          return this.modelValue.condition ?? "";
        }
      },
      set(val: string) {
        if (this.modelValue.type == "defined") {
          let relTable = this.activeTable?.relations.find((r) => r.column == val);
          this.$emit("update:model-value", {
            ...this.modelValue,
            foreignColumn: val,
            table: joinTableName(relTable?.referencedTableName ?? ""),
          });
        } else {
          this.$emit("update:model-value", {
            ...this.modelValue,
            condition: val,
          });
        }
      },
    },
    joinTable: {
      get(): string {
        return this.modelValue.table;
      },
      set(val: string) {
        this.$emit("update:model-value", {
          ...this.modelValue,
          table: val,
        });
      },
    },
  },
  mounted() {
    if (!this.value.id) {
      this.value.id = uuid();
    }
  },
  methods: {
    swapJoinType(type: string) {
      if (type == "defined") {
        this.value.type = "custom";
      } else {
        this.value.type = "defined";
      }
    },
  },
});
</script>
