<template>
  <div class="flex flex-col border border-gray-300 rounded-md select-none">
    <div class="flex flex-row max-lg:flex-wrap gap-2 border-b border-gray-300 p-2">
      <div
        class="p-1 border border-gray-400 bg-green-200 rounded-md"
        title="Abfrage starten"
        @click="$emit('query:run')"
      >
        <PlayIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
      </div>
      <div
        class="p-1 border border-gray-400 bg-gray-100 rounded-md"
        title="Ergebnisse exportieren"
        @click="$emit('results:export')"
      >
        <ArchiveBoxArrowDownIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
      </div>
      <div
        class="p-1 border border-gray-400 bg-red-200 rounded-md"
        title="Ergebnisse leeren"
        @click="$emit('results:clear')"
      >
        <NoSymbolIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
      </div>
      <div class="p-1 border border-gray-400 bg-red-200 rounded-md" title="Anfrage löschen" @click="clearQuery">
        <TrashIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
      </div>
      <div class="grow"></div>
      <div
        v-if="allowPredefinedSelect && can('read', 'settings', 'query_store')"
        class="flex flex-row gap-2 max-lg:w-full max-lg:order-10"
      >
        <select v-model="activeQueryId" class="max-h-[34px] !py-0">
          <option :value="undefined" disabled>gepeicherte Anfrage auswählen</option>
          <option v-for="query in queries" :key="query.id" :value="query.id" @click="value = query.query">
            {{ query.title }}
          </option>
        </select>
        <div
          v-if="can('create', 'settings', 'query_store')"
          class="p-1 border border-gray-400 bg-gray-100 rounded-md"
          title="Abfrage speichern"
          @click="$emit('query:save')"
        >
          <InboxArrowDownIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
        </div>
      </div>
      <div class="grow max-lg:hidden"></div>
      <div class="p-1 border border-gray-400 bg-gray-100 rounded-md" title="Schema-Struktur" @click="showStructure">
        <SparklesIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
      </div>
      <div class="flex flex-row min-w-fit overflow-hidden border border-gray-400 rounded-md">
        <div
          class="p-1"
          :class="typeof value == 'object' ? 'bg-gray-200' : ''"
          title="Visual Builder"
          @click="queryMode = 'builder'"
        >
          <RectangleGroupIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
        </div>
        <div
          class="p-1"
          :class="typeof value == 'string' ? 'bg-gray-200' : ''"
          title="SQL Editor"
          @click="queryMode = 'editor'"
        >
          <CommandLineIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
        </div>
      </div>
    </div>
    <div class="p-2 h-44 md:h-60 w-full overflow-y-auto">
      <textarea v-if="typeof value == 'string'" v-model="value" placeholder="SQL Query" class="h-full w-full" />
      <Table v-else v-model="value" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, defineComponent, markRaw, type PropType } from "vue";
import { mapActions, mapState, mapWritableState } from "pinia";
import type { DynamicQueryStructure } from "@/types/dynamicQueries";
import {
  ArchiveBoxArrowDownIcon,
  CommandLineIcon,
  InboxArrowDownIcon,
  NoSymbolIcon,
  PlayIcon,
  RectangleGroupIcon,
  TrashIcon,
  SparklesIcon,
} from "@heroicons/vue/24/outline";
import { useQueryBuilderStore } from "@/stores/admin/club/queryBuilder";
import { useModalStore } from "@/stores/modal";
import Table from "./Table.vue";
import { useAbilityStore } from "@/stores/ability";
import { useQueryStoreStore } from "@/stores/admin/settings/queryStore";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    modelValue: {
      type: [Object, String] as PropType<DynamicQueryStructure | string>,
      default: {
        select: "*",
        table: "",
        where: [],
        join: [],
        orderBy: [],
      },
    },
    allowPredefinedSelect: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["update:model-value", "query:run", "query:save", "results:export", "results:clear"],
  watch: {
    queryMode() {
      if (this.queryMode == "builder") {
        this.value = {
          select: "*",
          table: "",
          where: [],
          join: [],
          orderBy: [],
        };
      } else {
        this.value = "";
      }
      this.activeQueryId = undefined;
    },
    activeQueryId() {
      let query = this.queries.find((t) => t.id == this.activeQueryId)?.query;
      if (query != undefined) {
        if (typeof query == "string") {
          this.queryMode = "editor";
        } else {
          this.queryMode = "builder";
        }
        this.value = query;
      }
    },
  },
  data() {
    return {
      autoChangeFlag: false as boolean,
      queryMode: "builder" as "builder" | "editor",
    };
  },
  computed: {
    ...mapState(useAbilityStore, ["can"]),
    ...mapState(useQueryBuilderStore, ["tableMetas", "loading"]),
    ...mapWritableState(useQueryBuilderStore, ["activeQueryId"]),
    ...mapState(useQueryStoreStore, ["queries"]),
    value: {
      get() {
        return this.modelValue;
      },
      set(val: DynamicQueryStructure) {
        this.$emit("update:model-value", val);
      },
    },
  },
  mounted() {
    this.fetchTableMetas();
    this.fetchQueries();
  },
  methods: {
    ...mapActions(useModalStore, ["openModal"]),
    ...mapActions(useQueryBuilderStore, ["fetchTableMetas"]),
    ...mapActions(useQueryStoreStore, ["fetchQueries"]),
    clearQuery() {
      this.$emit("update:model-value", undefined);
      this.activeQueryId = undefined;
      if (typeof this.value != "string") {
        this.value = {
          select: "*",
          table: "",
          where: [],
          join: [],
          orderBy: [],
        };
      } else {
        this.value = "";
      }
    },
    showStructure() {
      this.openModal(markRaw(defineAsyncComponent(() => import("@/components/queryBuilder/StructureModal.vue"))));
    },
  },
});
</script>
