<script setup>
import dayjs from "dayjs"
const props = defineProps({
  type: {
    type: String,
    required: false,
    default: null
  },
  elementId: {
    type: String,
    required: false,
    default: null
  },
  renderHeadline: {
    type: Boolean,
    default: false
  },
  search: {
    type: String,
    required: false,
    default: ""
  }
})

const auth = useAuthStore()

const toast = useToast()
const showAddHistoryItemModal = ref(false)
const colorMode = useColorMode()

const items = ref([])
const platform = ref("default")

const setup = async () => {
  if(props.type && props.elementId){
    items.value = await useNuxtApp().$api(`/api/resource/${props.type}/${props.elementId}/history`)
  } else {
    items.value = await useNuxtApp().$api(`/api/history`)
  }
}

setup()



const addHistoryItemData = ref({
  text: ""
})

const addHistoryItem = async () => {
  if (!props.type || !props.elementId) {
    toast.add({ title: "Im zentralen Logbuch können keine direkten Einträge erstellt werden." })
    return
  }

  const res = await useNuxtApp().$api(`/api/resource/${props.type}/${props.elementId}/history`, {
    method: "POST",
    body: addHistoryItemData.value
  })




  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
}

const filteredItems = computed(() => {
  const search = props.search.trim().toLowerCase()

  if (!search) return items.value

  return items.value.filter((item) => {
    return [
      item.text,
      item.created_by_profile?.full_name,
      item.created_by ? "" : "FEDEO Bot",
      dayjs(item.created_at).format("DD.MM.YY HH:mm")
    ].some((value) => String(value || "").toLowerCase().includes(search))
  })
})

</script>

<template>
  <UModal
    v-model:open="showAddHistoryItemModal"

  >
    <template #content>
      <UCard class="h-full">
        <template #header>
          <div class="flex items-center justify-between">
            <h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
              Eintrag hinzufügen
            </h3>
            <UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1" @click="showAddHistoryItemModal = false" />
          </div>
        </template>

        <UFormField
          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>-->

        </UFormField>


        <template #footer>
          <UButton @click="addHistoryItem">Speichern</UButton>
        </template>
      </UCard>
    </template>
  </UModal>
  <Toolbar
      v-if="!props.renderHeadline && props.elementId && props.type"
  >
    <UButton
        @click="showAddHistoryItemModal = true"
    >
      + Eintrag
    </UButton>
  </Toolbar>
  <div v-else-if="props.renderHeadline && props.elementId && props.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>
    <USeparator class="my-3"/>
  </div>

  <!-- ITEM LIST  -->
  <div style="height: 90%; overflow-y: scroll">
    <div
        v-if="filteredItems.length > 0"
        v-for="(item,index) in filteredItems.slice().reverse()"
    >
      <USeparator
          class="my-3"
          v-if="index !== 0"
      />
      <div class="flex items-center gap-3">
        <UAvatar
            v-if="!item.created_by"
            :src="colorMode.value === 'light' ? '/Logo.png' : '/Logo_Dark.png' "
        />
        <UAvatar
            :alt="item.created_by_profile?.full_name"
            v-else
        />
        <div>
          <h3 v-if="item.created_by">{{item.created_by_profile?.full_name}}</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>
    <UAlert
        v-else
        color="neutral"
        variant="soft"
        icon="i-heroicons-magnifying-glass"
        title="Keine Logbucheinträge gefunden."
        description="Passe die Suche an, um weitere Einträge zu sehen."
    />
  </div>



</template>

<style scoped>

</style>
