<script setup>

import EntityShowSubTimes from "~/components/EntityShowSubTimes.vue";
import WikiEntityWidget from "~/components/wiki/WikiEntityWidget.vue";
import LabelPrintModal from "~/components/LabelPrintModal.vue";

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

const {type} = props

defineShortcuts({
  'backspace': () => {
    router.back()
  },
  'arrowleft': () => {
    const currentIndex = Number(openTab.value)
    if(currentIndex > 0){
      openTab.value = String(currentIndex - 1)
      router.push(`${router.currentRoute.value.path}?tabIndex=${openTab.value}`)
    }
  },
  'arrowright': () => {
    const currentIndex = Number(openTab.value)
    if(currentIndex < dataType.showTabs.length - 1) {
      openTab.value = String(currentIndex + 1)
      router.push(`${router.currentRoute.value.path}?tabIndex=${openTab.value}`)
    }
  },
})

const emit = defineEmits(["updateNeeded"])

const router = useRouter()
const route = useRoute()
const dataStore = useDataStore()
const modal = useModal()
const auth = useAuthStore()
const toast = useToast()

const dataType = dataStore.dataTypes[type]

const openTab = ref(String(route.query.tabIndex || 0))
const portalInviteLoading = ref(false)



const getAvailableQueryStringData = (keys) => {
  let returnString =""

  function addParam (key,value) {
    if(returnString.length  === 0) {
      returnString += `${key}=${value}`
    } else {
      returnString += `&${key}=${value}`

    }
  }


  if(props.item.customer) {
    addParam("customer", props.item.customer.id)
  } else if(type === "customers" || type === "members") {
    addParam("customer", props.item.id)
  }

  if(props.item.project) {
    addParam("project", props.item.project.id)
  } else if(type === "projects") {
    addParam("project", props.item.id)
  }

  if(props.item.plant) {
    addParam("plant", props.item.plant.id)
  } else if(type === "plants") {
    addParam("plant", props.item.id)
  }

  if(keys) {
    Object.keys(keys).forEach(key => {
      addParam(key, keys[key])
    })
  }

  return returnString

}

const onTabChange = (index) => {
  openTab.value = String(index)
  router.push(`${router.currentRoute.value.path}?tabIndex=${openTab.value}`)
}

const changePinned = async () => {
  let newPins = []

  if(auth.profile.pinned_on_navigation.find(i => i.datatype === type && i.id === props.item.id)){
    //Remove Pin

    newPins = auth.profile.pinned_on_navigation.filter(i => !(i.datatype === type && i.id === props.item.id))
  } else {
    //Add Pin

    newPins = [
        ...auth.profile.pinned_on_navigation,
      {
        id: props.item.id,
        icon: "i-heroicons-document",
        type: "standardEntity",
        datatype: type,
        label: props.item[dataType.templateColumns.find(i => i.title).key]
      }
    ]
  }

  const res = await useNuxtApp().$api(`/api/user/${auth.user.id}/profile`,{
    method: "PUT",
    body: {
      data: {
        pinned_on_navigation: newPins
      }
    }
  })

  await auth.fetchMe()



}

const openCustomerInventoryLabelPrint = () => {
  modal.open(LabelPrintModal, {
    context: {
      id: props.item.id,
      customerInventoryId: props.item.customerInventoryId,
      name: props.item.name,
      customerName: props.item.customer?.name,
      serialNumber: props.item.serialNumber
    }
  })
}

const invitePortalUser = async () => {
  if (type !== "customers" || !props.item?.id) return

  portalInviteLoading.value = true

  try {
    const response = await useAdmin().invitePortalUser(Number(props.item.id))
    toast.add({
      title: "Portal-Einladung versendet",
      description: `E-Mail: ${response.email}${response.initialPassword ? ` | Initialpasswort: ${response.initialPassword}` : ""}`,
      timeout: 9000
    })
    emit("updateNeeded")
  } catch (err) {
    toast.add({
      title: "Portal-Einladung fehlgeschlagen",
      description: err?.data?.error || "Die Einladung konnte nicht erstellt werden.",
      color: "error",
      timeout: 7000
    })
  } finally {
    portalInviteLoading.value = false
  }
}

</script>

<template>
  <UDashboardNavbar
      v-if="props.inModal"
      :ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
  >
    <template #center>
      <h1
          v-if="item"
          :class="['text-xl','font-medium']"
      >{{item ? `${dataType.labelSingle}${props.item[dataType.templateColumns.find(i => i.title).key] ? ': ' + props.item[dataType.templateColumns.find(i => i.title).key] : ''}`: '' }}</h1>
    </template>
    <template #right>
      <UButton
          @click="modal.close()"
          color="red"
          class="ml-2"
          icon="i-heroicons-x-mark"
          variant="outline"
      />
    </template>
  </UDashboardNavbar>
  <UDashboardNavbar
      v-else-if="!props.inModal && platform !== 'mobile'"
      :ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
  >
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.back()/*router.push(`/standardEntity/${type}`)*/"
      >
          Zurück
      </UButton>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="router.push(`/standardEntity/${type}`)"
      >
          Übersicht
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="item"
          :class="['text-xl','font-medium']"
      >{{item ? `${dataType.labelSingle}${props.item[dataType.templateColumns.find(i => i.title).key] ? ': ' + props.item[dataType.templateColumns.find(i => i.title).key] : ''}`: '' }}</h1>
    </template>
    <template #right>
      <UButton
          v-if="auth.profile"
        :variant="auth.profile?.pinned_on_navigation.find(i => i.datatype === type && i.id === props.item.id) ? 'solid' : 'outline'"
        icon="i-heroicons-star"
        color="yellow"
        @click="changePinned"
      ></UButton>
      <UButton
          v-if="type === 'customerinventoryitems'"
          icon="i-heroicons-printer"
          variant="outline"
          @click="openCustomerInventoryLabelPrint"
      >
        Label
      </UButton>
      <UButton
          v-if="type === 'customers' && auth.user?.is_admin"
          icon="i-heroicons-envelope"
          variant="outline"
          :loading="portalInviteLoading"
          @click="invitePortalUser"
      >
        Portal einladen
      </UButton>
      <UButton
          @click="router.push(`/standardEntity/${type}/edit/${item.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UDashboardNavbar
      v-else-if="!props.inModal && platform === 'mobile'"
      :ui="{center: 'flex items-stretch gap-1.5 min-w-0'}"
  >
    <template #toggle>
      <div></div>
    </template>
    <template #center>
      <h1
          v-if="item"
          :class="['text-xl','font-medium','text-truncate']"
      >{{item ? `${dataType.labelSingle}${props.item[dataType.templateColumns.find(i => i.title).key] ? ': ' + props.item[dataType.templateColumns.find(i => i.title).key] : ''}`: '' }}</h1>
    </template>
    <template #right>
      <UButton
          v-if="type === 'customerinventoryitems'"
          icon="i-heroicons-printer"
          variant="outline"
          @click="openCustomerInventoryLabelPrint"
      >
        Label
      </UButton>
      <UButton
          v-if="type === 'customers' && auth.user?.is_admin"
          icon="i-heroicons-envelope"
          variant="outline"
          :loading="portalInviteLoading"
          @click="invitePortalUser"
      >
        Portal einladen
      </UButton>
      <UButton
          @click="router.push(`/standardEntity/${type}/edit/${item.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UTabs
      :items="dataType.showTabs"
      v-if="props.item.id && platform !== 'mobile'"
      class="p-5"
      v-model="openTab"
      @update:model-value="onTabChange"
  >
    <template #content="{item:tab}">
      <div v-if="tab.label === 'Informationen'" class="flex flex-row">

        <EntityShowSubInformation
            :top-level-type="type"
            :item="props.item"
            class="w-1/2 mr-5"
            :platform="platform"
        />

        <EntityShowSubHistoryDisplay
            :top-level-type="type"
            :item="props.item"
            class="w-1/2"
            :platform="platform"
        />
      </div>

      <EntityShowSubFiles
          :item="props.item"
          :query-string-data="getAvailableQueryStringData()"
          v-else-if="tab.label === 'Dateien'"
          :top-level-type="type"
          type="files"
          @updateNeeded="emit('updateNeeded')"
          :platform="platform"
      />
      <!-- TODO Change Active Phase      -->
      <EntityShowSubPhases
          :item="props.item"
          :top-level-type="type"
          v-else-if="tab.label === 'Phasen'"
          :query-string-data="getAvailableQueryStringData()"
          @updateNeeded="emit('updateNeeded')"
          :platform="platform"
      />
     <EntityShowSubCreatedDocuments
          :item="props.item"
          :top-level-type="type"
          v-else-if="tab.label === 'Ausgangsbelege'"
          :query-string-data="getAvailableQueryStringData()"
          :platform="platform"
      />
       <EntityShowSubCostCentreReport
          :top-level-type="type"
          :item="props.item"
          v-else-if="tab.label === 'Auswertung Kostenstelle'"
          :platform="platform"
      />
      <EntityShowSubOwnAccountsStatements
          :top-level-type="type"
          :item="props.item"
          v-else-if="tab.label === 'Buchungen'"
          :platform="platform"
      />
      <EntityShowSubTimes
          :top-level-type="type"
          :item="props.item"
          v-else-if="tab.label === 'Zeiten'"
          :platform="platform"
      />
      <div v-else-if="tab.label === 'Wiki'" class="h-[600px] w-full overflow-hidden">
        <WikiEntityWidget
            :entity-type="type"
            :entity-id="typeof props.item.id === 'number' ? props.item.id : undefined"
            :entity-uuid="typeof props.item.id === 'string' ? props.item.id : undefined"
        />
      </div>
      <EntityShowSub
          :item="props.item"
          :query-string-data="getAvailableQueryStringData()"
          :tab-label="tab.label"
          :top-level-type="type"
          :type="tab.key"
          v-else
          :platform="platform"
      />
    </template>
  </UTabs>
  <UDashboardPanelContent v-else style="overflow-x: hidden;">
    <div v-for="sub in dataType.showTabs" :key="sub.key">
      <div v-if="sub.label === 'Informationen'">

        <EntityShowSubInformation
            :top-level-type="type"
            :item="props.item"
            :platform="platform"
        />

        <EntityShowSubHistoryDisplay
            :top-level-type="type"
            :item="props.item"
            :platform="platform"
        />
      </div>

      <EntityShowSubFiles
          :item="props.item"
          :query-string-data="getAvailableQueryStringData()"
          v-else-if="sub.label === 'Dateien'"
          :top-level-type="type"
          type="files"
          @updateNeeded="emit('updateNeeded')"
          :platform="platform"
      />
      <!--<EntityShowSubPhases
          :item="props.item"
          :top-level-type="type"
          v-else-if="sub.label === 'Phasen'"
          :query-string-data="getAvailableQueryStringData()"
          @updateNeeded="emit('updateNeeded')"
          :platform="platform"
      />
      <EntityShowSubCreatedDocuments
          :item="props.item"
          :top-level-type="type"
          v-else-if="sub.label === 'Ausgangsbelege'"
          :query-string-data="getAvailableQueryStringData()"
          :platform="platform"
      />
      <EntityShowSubCostCentreReport
          :top-level-type="type"
          :item="props.item"
          v-else-if="sub.label === 'Auswertung Kostenstelle'"
          :platform="platform"
      />

      <EntityShowSub
          :item="props.item"
          :query-string-data="getAvailableQueryStringData()"
          :tab-label="sub.label"
          :top-level-type="type"
          v-else
          :platform="platform"
      />-->
    </div>

  </UDashboardPanelContent>

</template>

<style scoped>


</style>
