<template>
  <MainTemplate>
    <template #topBar>
      <div class="flex flex-row items-center justify-between pt-5 pb-3 px-7">
        <h1 class="font-bold text-xl h-8">Query Builder</h1>
      </div>
    </template>
    <template #diffMain>
      <div class="flex flex-col w-full h-full gap-2 px-7 overflow-y-auto">
        <BuilderHost
          v-model="query"
          allow-predefined-select
          @query:run="sendQuery"
          @query:save="triggerSave"
          @results:clear="clearResults"
          @results:export="exportData"
        />
        <p>Ergebnisse:</p>
        <div
          v-if="loadingData == 'failed'"
          class="flex flex-col p-2 border border-red-600 bg-red-200 rounded-md select-none"
        >
          <p v-if="typeof queryError == 'string'">
            {{ queryError }}
          </p>
          <div v-else>
            <p>
              CODE: <br />
              {{ queryError.code }}
            </p>
            <br />
            <p>
              MSG: <br />
              {{ queryError.msg }}
            </p>
            <br />
            <p>
              RESULTING SQL: <br />
              {{ queryError.sql }}
            </p>
          </div>
        </div>
        <Pagination
          v-else
          :items="data"
          :totalCount="totalLength"
          :indicateLoading="loadingData == 'loading'"
          @load-data="(offset, count) => sendQuery(offset, count)"
        >
          <template #pageRow="{ row }: { row: { id: FieldType; [key: string]: FieldType } }">
            <p>{{ row }}</p>
          </template>
        </Pagination>
      </div>
    </template>
  </MainTemplate>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapActions, mapState, mapWritableState } from "pinia";
import MainTemplate from "@/templates/Main.vue";
import Pagination from "@/components/Pagination.vue";
import { useQueryBuilderStore } from "@/stores/admin/club/queryBuilder";
import BuilderHost from "@/components/queryBuilder/BuilderHost.vue";
import type { DynamicQueryStructure, FieldType } from "@/types/dynamicQueries";
import { useQueryStoreStore } from "@/stores/admin/settings/queryStore";
</script>

<script lang="ts">
export default defineComponent({
  computed: {
    ...mapState(useQueryBuilderStore, ["loading", "loadingData", "tableMetas", "data", "totalLength", "queryError"]),
    ...mapWritableState(useQueryBuilderStore, ["query"]),
  },
  mounted() {
    this.fetchTableMetas();
  },
  methods: {
    ...mapActions(useQueryBuilderStore, ["fetchTableMetas", "sendQuery", "clearResults", "exportData"]),
    ...mapActions(useQueryStoreStore, ["triggerSave"]),
  },
});
</script>
