<script setup>
import dayjs from "dayjs"
const props = defineProps({
  type: {
    type: String
  },
  elementId: {
    type: String
  },
  renderHeadline: {
    type: Boolean
  }
})
const { metaSymbol } = useShortcuts()
const profileStore = useProfileStore()
const user = useSupabaseUser()
const supabase = useSupabaseClient()
const toast = useToast()
const {type, elementId} = props
const showAddHistoryItemModal = ref(false)
const colorMode = useColorMode()

const items = ref([])

const setup = async () => {

  if(type && elementId){
    items.value = (await supabase.from("historyitems").select().eq(type,elementId).order("created_at",{ascending: true})).data || []
  } else {
    items.value = (await supabase.from("historyitems").select().order("created_at",{ascending: true})).data || []

  }
}

setup()



const addHistoryItemData = ref({
  text: "",
  config: {
    type: type,
    id: elementId
  }
})

const addHistoryItem = async () => {
  console.log(addHistoryItemData.value)
  addHistoryItemData.value.createdBy = profileStore.activeProfile.id

  addHistoryItemData.value[type] = elementId

  const {data,error} = await supabase
      .from("historyitems")
      .insert([{...addHistoryItemData.value, tenant: profileStore.currentTenant}])
      .select()

  if(error) {
    console.log(error)
  } else {
    if(addHistoryItemData.value.text.includes("@")){
      let usernames = [...addHistoryItemData.value.text.matchAll(/@(\S*)/gm)]

      const {data:profiles} = await supabase.from("profiles").select("id,username")

      let notifications = usernames.map(i => {
        let rawUsername = i[1]

        return {
          tenant: profileStore.currentTenant,
          profile: profiles.find(x => x.username === rawUsername).id,
          initiatingProfile: profileStore.activeProfile.id,
          title: "Sie wurden im Logbuch erwähnt",
          link: `/${type}s/show/${elementId}`,
          message: addHistoryItemData.value.text
        }
      })

      console.log(notifications)

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

    addHistoryItemData.value = {}
    toast.add({title: "Eintrag erfolgreich erstellt"})
    showAddHistoryItemModal.value = false
    await setup()
  }

}

const renderText = (text) => {
  const regex = /(@\w*)/g

  text = text.replaceAll(regex, "<a class='text-primary-500'>$&</a>")

  return text
}

</script>

<template>
  <UModal
    v-model="showAddHistoryItemModal"
  >
    <UCard>
      <template #header>
        Eintrag hinzufügen
      </template>

      <UFormGroup
        label="Text:"
      >
        <UTextarea
          v-model="addHistoryItemData.text"
          @keyup.meta.enter="addHistoryItem"
        />
<!-- TODO: Add Dropdown and Checking for Usernames  -->
<!--        <template #help>
          <UKbd>{{metaSymbol}}</UKbd> <UKbd>Enter</UKbd> Speichern
        </template>-->

      </UFormGroup>


      <template #footer>
        <UButton @click="addHistoryItem">Speichern</UButton>
      </template>
    </UCard>
  </UModal>
  <Toolbar
      v-if="!renderHeadline && elementId && type"
  >
    <UButton
        @click="showAddHistoryItemModal = true"
    >
      + Eintrag
    </UButton>
  </Toolbar>
  <div v-else-if="renderHeadline && elementId && type">
    <div :class="`flex justify-between`">
      <p class=""><span class="text-xl">Logbuch</span> <UBadge variant="outline">{{items.length}}</UBadge></p>
      <UButton
          @click="showAddHistoryItemModal = true"
      >
        + Eintrag
      </UButton>
    </div>
    <UDivider class="my-3"/>
  </div>

  <!-- ITEM LIST  -->
  <div style="height: 90%; overflow-y: scroll">
    <div
        v-if="items.length > 0"
        v-for="(item,index) in items.slice().reverse()"
    >
      <UDivider
          class="my-3"
          v-if="index !== 0"
      />
      <div class="flex items-center gap-3">
        <UAvatar
            v-if="!item.createdBy"
            :src="colorMode.value === 'light' ? '/Logo.png' : '/Logo_Dark.png' "
        />
        <UAvatar
            :alt="profileStore.getProfileById(item.createdBy).fullName"
            v-else
        />
        <div>
          <h3 v-if="item.createdBy">{{profileStore.getProfileById(item.createdBy) ? profileStore.getProfileById(item.createdBy).fullName : ""}}</h3>
          <h3 v-else>FEDEO Bot</h3>
          <span v-html="renderText(item.text)"/><br>
          <span class="text-gray-500">{{dayjs(item.created_at).format("DD.MM.YY HH:mm")}}</span>
        </div>
      </div>
    </div>
  </div>



</template>

<style scoped>

</style>