<script setup>
import dayjs from "dayjs";

const props = defineProps({
  type: {
    required: true,
    type: String
  },
  item: {
    required: true,
    type: Object
  }
})


const {type} = props

defineShortcuts({
  'backspace': () => {
    router.push(`/${type}`)
  },
  'arrowleft': () => {
    if(openTab.value > 0){
      openTab.value -= 1
    }
  },
  'arrowright': () => {
    if(openTab.value < 3) {
      openTab.value += 1
    }
  },
})


const router = useRouter()
const route = useRoute()
const dataStore = useDataStore()
const profileStore = useProfileStore()
const supabase = useSupabaseClient()

const dataType = dataStore.dataTypes[type]
const openTab = ref(0)

const item = ref(JSON.parse(props.item))
console.log(item.value)

const oldItem = ref(null)
const generateOldItemData = () => {
  oldItem.value = JSON.parse(props.item)
}
generateOldItemData()


const setupCreate = () => {
  dataType.templateColumns.forEach(datapoint => {
    if(datapoint.key.includes(".")){
      !item.value[datapoint.key.split(".")[0]] ? item.value[datapoint.key.split(".")[0]] = {} : null
    }

    if(datapoint.inputType === "editor") {
      if(datapoint.key.includes(".")){
        item[datapoint.key.split(".")[0]][datapoint.key.split(".")[1]] = {}
      } else {
        item[datapoint.key] = {}
      }


    }

  })
}
setupCreate()

const setupQuery = () => {
  if(route.query) {

    Object.keys(route.query).forEach(key => {
      if(["customer","contract","plant","contact"].includes(key)){
        item[key] = Number(route.query[key])
      } else {
        item[key] = route.query[key]
      }
    })
  }
}
setupQuery()

const loadedOptions = ref({})
const loadOptions = async () => {
  let optionsToLoad = dataType.templateColumns.filter(i => i.selectDataType).map(i => {
    return {
      option: i.selectDataType,
      key: i.key
    }
  })

  for await(const option of optionsToLoad) {
    if(option.option === "countrys") {
      loadedOptions.value[option.option] = (await supabase.from("countrys").select()).data
    } else if(option.option === "units") {
      loadedOptions.value[option.option] = (await supabase.from("units").select()).data
    } else {
      loadedOptions.value[option.option] = (await useSupabaseSelect(option.option))

      if(dataType.templateColumns.find(x => x.key === option.key).selectDataTypeFilter){
        loadedOptions.value[option.option] = loadedOptions.value[option.option].filter(i => dataType.templateColumns.find(x => x.key === option.key).selectDataTypeFilter(i, item))
      }
    }
  }
}

loadOptions()

const contentChanged = (content, datapoint) => {
  if(datapoint.key.includes(".")){
    item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]].html = content.html
    item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]].text = content.text
    item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]].json = content.json
  } else {
    item[datapoint.key].html = content.html
    item[datapoint.key].text = content.text
    item[datapoint.key].json = content.json
  }
}

</script>

<template>
  <UDashboardNavbar
      :ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
  >
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/standardEntity/${type}`)"
      >
        {{dataType.label}}
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="item"
          :class="['text-xl','font-medium']"
      >{{item.id ? `${dataType.labelSingle} bearbeiten` : `${dataType.labelSingle} erstellen` }}</h1>
    </template>
    <template #right>
      <UButton
          v-if="item.id"
          @click="dataStore.updateItem(type,item, oldItem)"
      >
        Speichern
      </UButton>
      <UButton
          v-else
          @click="dataStore.createNewItem(type,item)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="router.push(item.id ? `/standardEntity/${type}/show/${item.id}` : `/standardEntity/${type}`)"
          color="red"
          class="ml-2"
      >
        Abbrechen
      </UButton>
    </template>
  </UDashboardNavbar>
  <UDashboardPanelContent>
    <UForm
        class="p-5"
    >
      <div class="flex flex-row">
        <div
            v-for="columnName in dataType.inputColumns"
            class="w-1/2 mr-5"
        >
          <UDivider>{{columnName}}</UDivider>

          <!--
           Die Form Group darf nur in der ersten bearbeitet werden und muss dann runterkopiert werden
           -->

          <UFormGroup
              v-for="datapoint in dataType.templateColumns.filter(i => i.inputType && i.inputColumn === columnName)"
              :label="datapoint.label"
          >
            <template #help>
              <component
                  v-if="datapoint.helpComponent"
                  :is="datapoint.helpComponent"
                  :item="item"
              />
            </template>
            <div v-if="datapoint.key.includes('.')">
              <UInput
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-if="['text','number'].includes(datapoint.inputType)"
                  v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
                  :type="datapoint.inputType"
                  :placeholder="datapoint.inputIsNumberRange ? 'Leer lassen für automatisch generierte Nummer' : ''"
              >
                <template #trailing v-if="datapoint.inputTrailing">
                  <span class="text-gray-500 dark:text-gray-400 text-xs">{{datapoint.inputTrailing}}</span>
                </template>
              </UInput>
              <UToggle
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-else-if="datapoint.inputType === 'bool'"
                  v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              />
              <USelectMenu
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-else-if="datapoint.inputType === 'select'"
                  v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
                  :option-attribute="datapoint.selectOptionAttribute"
                  :value-attribute="datapoint.selectValueAttribute || 'id'"
                  :options="datapoint.selectManualOptions || loadedOptions[datapoint.selectDataType]"
                  :searchable="datapoint.selectSearchAttributes"
                  :search-attributes="datapoint.selectSearchAttributes"
                  :multiple="datapoint.selectMultiple"
              >
                <template #empty>
                  Keine Optionen verfügbar
                </template>
              </USelectMenu>
              <UTextarea
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-else-if="datapoint.inputType === 'textarea'"
                  v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
                  rows="4"
              />
              <UPopover :popper="{ placement: 'bottom-start' }" v-else-if="datapoint.inputType === 'date'">
                <UButton
                    icon="i-heroicons-calendar-days-20-solid"
                    :label="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]] ? dayjs(item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]).format('DD.MM.YYYY') : 'Datum auswählen'"
                    variant="outline"
                    :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"

                />

                <template #panel="{ close }">
                  <LazyDatePicker
                      @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                      v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]" @close="close"
                      :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
                  />
                </template>
              </UPopover>
              <!-- TODO: DISABLED FOR TIPTAP -->
              <Tiptap
                  v-else-if="datapoint.inputType === 'editor'"
                  @updateContent="(i) => contentChanged(i,datapoint)"
                  :preloadedContent="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]].html"
              />
            </div>
            <div v-else>
              <UInput
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-if="['text','number'].includes(datapoint.inputType)"
                  v-model="item[datapoint.key]"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
                  :type="datapoint.inputType"
                  :placeholder="datapoint.inputIsNumberRange ? 'Leer lassen für automatisch generierte Nummer' : ''"
              >
                <template #trailing v-if="datapoint.inputTrailing">
                  {{datapoint.inputTrailing}}
                </template>
              </UInput>
              <UToggle
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-else-if="datapoint.inputType === 'bool'"
                  v-model="item[datapoint.key]"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              />
              <USelectMenu
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-else-if="datapoint.inputType === 'select'"
                  v-model="item[datapoint.key]"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
                  :option-attribute="datapoint.selectOptionAttribute"
                  :value-attribute="datapoint.selectValueAttribute || 'id'"
                  :options="datapoint.selectManualOptions || loadedOptions[datapoint.selectDataType]"
                  :searchable="datapoint.selectSearchAttributes"
                  :search-attributes="datapoint.selectSearchAttributes"
                  :multiple="datapoint.selectMultiple"
                  searchable-placeholder="Suche..."
              >
                <template #empty>
                  Keine Optionen verfügbar
                </template>
              </USelectMenu>
              <UTextarea
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-else-if="datapoint.inputType === 'textarea'"
                  v-model="item[datapoint.key]"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
                  rows="4"
              />
              <UPopover :popper="{ placement: 'bottom-start' }" v-else-if="datapoint.inputType === 'date'">
                <UButton
                    icon="i-heroicons-calendar-days-20-solid"
                    :label="item[datapoint.key] ? dayjs(item[datapoint.key]).format('DD.MM.YYYY') : 'Datum auswählen'"
                    variant="outline"
                    :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
                />

                <template #panel="{ close }">
                  <LazyDatePicker
                      @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                      v-model="item[datapoint.key]" @close="close"
                      :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
                  />
                </template>
              </UPopover>
              <Tiptap
                  v-else-if="datapoint.inputType === 'editor'"
                  @updateContent="(i) => contentChanged(i,datapoint)"
                  :preloadedContent="item[datapoint.key].html"
              />
            </div>
            <div
                v-if="profileStore.ownTenant.ownFields"
            >
              <UDivider
                  class="mt-3"
              >Eigene Felder</UDivider>

              <UFormGroup
                  v-for="field in profileStore.ownTenant.ownFields.contracts"
                  :key="field.key"
                  :label="field.label"
              >
                <UInput
                    v-if="field.type === 'text'"
                    v-model="item.ownFields[field.key]"
                />
                <USelectMenu
                    v-else-if="field.type === 'select'"
                    :options="field.options"
                    v-model="item.ownFields[field.key]"
                />
              </UFormGroup>
            </div>

          </UFormGroup>
        </div>
      </div>
      <UFormGroup
          v-for="datapoint in dataType.templateColumns.filter(i => i.inputType)"
          :label="datapoint.label"
      >
        <template #help>
          <component
              v-if="datapoint.helpComponent"
              :is="datapoint.helpComponent"
              :item="item"
          />
        </template>
        <div v-if="datapoint.key.includes('.')">
          <UInput
              @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
              v-if="['text','number'].includes(datapoint.inputType)"
              v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]"
              :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              :type="datapoint.inputType"
              :placeholder="datapoint.inputIsNumberRange ? 'Leer lassen für automatisch generierte Nummer' : ''"
          >
            <template #trailing v-if="datapoint.inputTrailing">
              <span class="text-gray-500 dark:text-gray-400 text-xs">{{datapoint.inputTrailing}}</span>
            </template>
          </UInput>
          <UToggle
              @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
              v-else-if="datapoint.inputType === 'bool'"
              v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]"
              :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
          />
          <USelectMenu
              @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
              v-else-if="datapoint.inputType === 'select'"
              v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]"
              :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              :option-attribute="datapoint.selectOptionAttribute"
              :value-attribute="datapoint.selectValueAttribute || 'id'"
              :options="datapoint.selectManualOptions || loadedOptions[datapoint.selectDataType]"
              :searchable="datapoint.selectSearchAttributes"
              :search-attributes="datapoint.selectSearchAttributes"
              :multiple="datapoint.selectMultiple"
          >
            <template #empty>
              Keine Optionen verfügbar
            </template>
          </USelectMenu>
          <UTextarea
              @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
              v-else-if="datapoint.inputType === 'textarea'"
              v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]"
              :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              rows="4"
          />
          <UPopover :popper="{ placement: 'bottom-start' }" v-else-if="datapoint.inputType === 'date'">
            <UButton
                icon="i-heroicons-calendar-days-20-solid"
                :label="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]] ? dayjs(item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]).format('DD.MM.YYYY') : 'Datum auswählen'"
                variant="outline"
                :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"

            />

            <template #panel="{ close }">
              <LazyDatePicker
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-model="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]]" @close="close"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              />
            </template>
          </UPopover>
          <!-- TODO: DISABLED FOR TIPTAP -->
          <Tiptap
              v-else-if="datapoint.inputType === 'editor'"
              @updateContent="(i) => contentChanged(i,datapoint)"
              :preloadedContent="item[datapoint.key.split('.')[0]][datapoint.key.split('.')[1]].html"
          />
        </div>
        <div v-else>
          <UInput
              @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
              v-if="['text','number'].includes(datapoint.inputType)"
              v-model="item[datapoint.key]"
              :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              :type="datapoint.inputType"
              :placeholder="datapoint.inputIsNumberRange ? 'Leer lassen für automatisch generierte Nummer' : ''"
          >
            <template #trailing v-if="datapoint.inputTrailing">
              {{datapoint.inputTrailing}}
            </template>
          </UInput>
          <UToggle
              @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
              v-else-if="datapoint.inputType === 'bool'"
              v-model="item[datapoint.key]"
              :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
          />
          <USelectMenu
              @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
              v-else-if="datapoint.inputType === 'select'"
              v-model="item[datapoint.key]"
              :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              :option-attribute="datapoint.selectOptionAttribute"
              :value-attribute="datapoint.selectValueAttribute || 'id'"
              :options="datapoint.selectManualOptions || loadedOptions[datapoint.selectDataType]"
              :searchable="datapoint.selectSearchAttributes"
              :search-attributes="datapoint.selectSearchAttributes"
              :multiple="datapoint.selectMultiple"
              searchable-placeholder="Suche..."
          >
            <template #empty>
              Keine Optionen verfügbar
            </template>
          </USelectMenu>
          <UTextarea
              @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
              v-else-if="datapoint.inputType === 'textarea'"
              v-model="item[datapoint.key]"
              :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              rows="4"
          />
          <UPopover :popper="{ placement: 'bottom-start' }" v-else-if="datapoint.inputType === 'date'">
            <UButton
                icon="i-heroicons-calendar-days-20-solid"
                :label="item[datapoint.key] ? dayjs(item[datapoint.key]).format('DD.MM.YYYY') : 'Datum auswählen'"
                variant="outline"
                :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
            />

            <template #panel="{ close }">
              <LazyDatePicker
                  @change="datapoint.inputChangeFunction ? datapoint.inputChangeFunction(item,loadedOptions) : null"
                  v-model="item[datapoint.key]" @close="close"
                  :disabled="datapoint.disabledFunction ? datapoint.disabledFunction(item) : false"
              />
            </template>
          </UPopover>
          <Tiptap
              v-else-if="datapoint.inputType === 'editor'"
              @updateContent="(i) => contentChanged(i,datapoint)"
              :preloadedContent="item[datapoint.key].html"
          />
        </div>
        <div
            v-if="profileStore.ownTenant.ownFields"
        >
          <UDivider
              class="mt-3"
          >Eigene Felder</UDivider>

          <UFormGroup
              v-for="field in profileStore.ownTenant.ownFields.contracts"
              :key="field.key"
              :label="field.label"
          >
            <UInput
                v-if="field.type === 'text'"
                v-model="item.ownFields[field.key]"
            />
            <USelectMenu
                v-else-if="field.type === 'select'"
                :options="field.options"
                v-model="item.ownFields[field.key]"
            />
          </UFormGroup>
        </div>

      </UFormGroup>
    </UForm>
  </UDashboardPanelContent>
</template>

<style scoped>
td {
  border-bottom: 1px solid lightgrey;
  vertical-align: top;
  padding-bottom: 0.15em;
  padding-top: 0.15em;
}
</style>