<script setup>

import {useFunctions} from "~/composables/useFunctions.js";
import dayjs from "dayjs";

const supabase = useSupabaseClient()
const profileStore = useProfileStore()
const toast = useToast()

const itemInfo = ref({})
const loaded = ref(false)

const setup = async () => {
  itemInfo.value = (await supabase.from("tickets").select("*, ticketmessages(*, profile(fullName, tenant, id)), created_by(*)").eq("id",useRoute().params.id).single()).data
  loaded.value = true
}

setup()

const messageContent = ref("")

const addMessage = async () => {
    const {data,error} = await supabase.from("ticketmessages").insert({
      profile: profileStore.activeProfile.id,
      content: messageContent.value,
      ticket: itemInfo.value.id,
      internal: false,
      type: "Nachricht"
    }).select().single()

    if(error) {
      toast.add({title: "Erstellen fehlgeschlagen", color: "rose"})
    } else {
      toast.add({title: "Erstellen erfolgreich"})
      messageContent.value=""
      setup()
      if(profileStore.currentTenant !== 5) {
        await useFunctions().useSendTelegramNotification(`Neue Nachricht im Ticket ${useRoute().params.id} von ${profileStore.activeProfile.fullName}: ${data.content}`)
      } else if(profileStore.activeProfile.id !== itemInfo.value.created_by) {

        let notification = {
          tenant: itemInfo.value.tenant,
          profile: itemInfo.value.created_by.id,
          initiatingProfile: profileStore.activeProfile.id,
          title: `Sie haben eine neue Nachricht von ${profileStore.activeProfile.fullName} im Ticket ${itemInfo.value.title}`,
          link: `/support/${itemInfo.value.id}`,
          message: data.content
        }

        console.log(notification)


        const {error} = await supabase.from("notifications").insert(notification)



      }

    }
}

const showAddEntryModal = ref(false)
const addEntryData = ref({})
const addEntry = async () => {
  const {data,error} = await supabase.from("ticketmessages").insert({
    profile: profileStore.activeProfile.id,
    content: addEntryData.value.content,
    ticket: itemInfo.value.id,
    internal: addEntryData.value.internal,
    type: addEntryData.value.type
  }).select().single()

  if(error) {
    toast.add({title: "Erstellen fehlgeschlagen", color: "rose"})
  } else {
    toast.add({title: "Erstellen erfolgreich"})
    addEntryData.value = {}
    setup()
    showAddEntryModal.value = false

  }
}

const closeTicket = async () => {
  const {data, error} = await supabase.from("tickets").update({status: "Geschlossen"}).eq("id",useRoute().params.id).single()

  if(error) {
    console.log(error)
  } else {
    console.log(data)

    addEntryData.value.type = "Notiz"
    addEntryData.value.internal = false
    addEntryData.value.content = `Ticket durch ${profileStore.activeProfile.fullName} geschlossen`

    addEntry()

  }

  setup()
}

</script>

<template>
  <UDashboardNavbar title="Support Ticket">
    <template #badge>
      <UBadge
        variant="outline"
        v-if="itemInfo.status === 'Offen'"
        color="yellow"
      >{{itemInfo.status}}</UBadge>
      <UBadge
        variant="outline"
        v-if="itemInfo.status === 'Geschlossen'"
        color="primary"
      >{{itemInfo.status}}</UBadge>
    </template>
    <template #center>
      {{itemInfo.title}}
    </template>
    <template #right>
      <UButton
        v-if="profileStore.currentTenant === 5"
        variant="outline"
        @click="closeTicket"
      >
        Ticket Schließen
      </UButton>
      <UButton
        v-if="profileStore.currentTenant === 5"
        variant="outline"
        @click="showAddEntryModal = true"
      >
        + Eintrag
      </UButton>
      <UModal v-model="showAddEntryModal">
        <UCard>
          <template #header>
            Eintrag hinzufügen
          </template>

          <UFormGroup
            label="Intern:"
          >
            <UToggle
              v-model="addEntryData.internal"
            />
          </UFormGroup>
          <UFormGroup
            label="Typ:"
          >
            <USelectMenu
              v-model="addEntryData.type"
              :options="['Nachricht','Notiz','Anruf','Externe Kommunikation']"
            />
          </UFormGroup>
          <UFormGroup
            label="Inhalt:"
          >
            <UTextarea
              v-model="addEntryData.content"
            />
          </UFormGroup>

          <template #footer>
            <UButton
              @click="addEntry"
            >
              Erstellen
            </UButton>
          </template>
        </UCard>
      </UModal>
    </template>
  </UDashboardNavbar>
  <UDashboardPanelContent v-if="loaded">
    <div
        v-if="profileStore.currentTenant === 5"
        v-for="item in itemInfo.ticketmessages"
        class="mb-3 flex flex-row p-5"
        :style="item.internal ? 'border: 1px solid red; border-radius: 15px' : item.profile.tenant === 5 ? 'border: 1px solid #69c350; border-radius: 15px' : 'border: 1px solid #fff; border-radius: 15px'"
    >
      <UAvatar :alt="item.profile.fullName" class="mr-3"/>
      <div>
        <p class="text-xl">{{item.type}} - {{item.profile.fullName}}</p>
        <p v-html="item.content"></p>
        <p class="mt-1 text-gray-600 dark:text-gray-400">{{dayjs(item.created_at).format("DD.MM.YYYY HH:mm")}}</p>
      </div>
    </div>



<!--    <UAlert
        v-if="profileStore.currentTenant === 5"
        v-for="item in itemInfo.ticketmessages"
        :avatar="{ alt: item.profile.fullName}"
        :title="`${item.type} - ${item.profile.fullName}`"
        class="mb-3"
        :color="item.internal ? 'rose' : item.profile.tenant === 5 ? 'primary' : 'white'"
        variant="outline"
    >
      <template #description>
        <span v-html="item.content"></span>
        <p class="mt-1 text-gray-600 dark:text-gray-400">{{dayjs(item.created_at).format("DD.MM.YYYY HH:mm")}}</p>
      </template>
    </UAlert>-->
    <UAlert
        v-else
        v-for="item in itemInfo.ticketmessages.filter(i => !i.internal)"
        :avatar="{ alt: item.profile.fullName}"
        :title="`${item.type} - ${item.profile.fullName}`"
        class="mb-3"
        :color="item.profile.tenant === 5 ? 'primary' : 'white'"
        variant="outline"
    >
      <template #description>
        <p>{{item.content}}</p>
        <p class="mt-1 text-gray-600 dark:text-gray-400">{{dayjs(item.created_at).format("DD.MM.YYYY HH:mm")}}</p>
      </template>
    </UAlert>

    <InputGroup>
      <UTextarea
        class="w-full mr-2"
        placeholder="Neue Nachricht senden"
        v-model="messageContent"
      />
      <UButton
        @click="addMessage"
      >
        Senden
      </UButton>
    </InputGroup>

  </UDashboardPanelContent>
  <UProgress animation="carousel" v-else class="w-3/4 mx-auto"/>



</template>

<style scoped>

</style>