<script setup>
import dayjs from "dayjs"
const props = defineProps({
  type: {
    required: true,
    type: String
  },
  elementId: {
    required: true,
    type: String
  },
  renderHeadline: {
    type: Boolean
  }
})
const { metaSymbol } = useShortcuts()
const dataStore = useDataStore()
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 === "customer") {
    items.value = (await supabase.from("historyitems").select().eq("customer",elementId)).data || []
  } else if(type === "vendor") {
    items.value = (await supabase.from("historyitems").select().eq("vendor",elementId)).data || []
  } else if(type === "project") {
    items.value = (await supabase.from("historyitems").select().eq("project",elementId)).data || []
  } else if(type === "plant") {
    items.value = (await supabase.from("historyitems").select().eq("plant",elementId)).data || []
  } else if(type === "incomingInvoice") {
    items.value = (await supabase.from("historyitems").select().eq("incomingInvoice",elementId)).data || []
  } else if(type === "document") {
    items.value = (await supabase.from("historyitems").select().eq("document",elementId)).data || []
  } else if(type === "contact") {
    items.value = (await supabase.from("historyitems").select().eq("contact",elementId)).data || []
  } else if(type === "contract") {
    items.value = (await supabase.from("historyitems").select().eq("contract",elementId)).data || []
  } else if(type === "inventoryitem") {
    items.value = (await supabase.from("historyitems").select().eq("inventoryitem",elementId)).data || []
  } else if(type === "product") {
    items.value = (await supabase.from("historyitems").select().eq("product",elementId)).data || []
  } else if(type === "profile") {
    items.value = (await supabase.from("historyitems").select().eq("profile",elementId)).data || []
  } else if(type === "absencerequest") {
    items.value = (await supabase.from("historyitems").select().eq("absenceRequest",elementId)).data || []
  } else if(type === "event") {
    items.value = (await supabase.from("historyitems").select().eq("event",elementId)).data || []
  } else if(type === "task") {
    items.value = (await supabase.from("historyitems").select().eq("task",elementId)).data || []
  } else if(type === "vehicle") {
    items.value = (await supabase.from("historyitems").select().eq("vehicle",elementId)).data || []
  } else if(type === "space") {
    items.value = (await supabase.from("historyitems").select().eq("space",elementId)).data || []
  } else if(type === "trackingtrip") {
    items.value = (await supabase.from("historyitems").select().eq("trackingtrip",elementId)).data || []
  }
}

setup()



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

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

  if(type === "customer") {
    addHistoryItemData.value.customer = elementId
  } else if(type === "vendor") {
    addHistoryItemData.value.vendor = elementId
  } else if(type === "project") {
    addHistoryItemData.value.project = elementId
  } else if(type === "plant") {
    addHistoryItemData.value.plant = elementId
  } else if(type === "incomingInvoice") {
    addHistoryItemData.value.incomingInvoice = elementId
  } else if(type === "document") {
    addHistoryItemData.value.document = elementId
  } else if(type === "contact") {
    addHistoryItemData.value.contact = elementId
  } else if(type === "contract") {
    addHistoryItemData.value.contract = elementId
  } else if(type === "inventoryitem") {
    addHistoryItemData.value.inventoryitem = elementId
  } else if(type === "product") {
    addHistoryItemData.value.product = elementId
  } else if(type === "profile") {
    addHistoryItemData.value.profile = elementId
  } else if(type === "absencerequest") {
    addHistoryItemData.value.absenceRequest = elementId
  } else if(type === "event") {
    addHistoryItemData.value.event = elementId
  } else if(type === "task") {
    addHistoryItemData.value.event = elementId
  } else if(type === "vehicle") {
    addHistoryItemData.value.vehicle = elementId
  } else if(type === "space") {
    addHistoryItemData.value.space = elementId
  } else if(type === "trackingtrip") {
    addHistoryItemData.value.trackingtrip = elementId
  }


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

  if(error) {
    console.log(error)
  } else {
    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"
        />
<!--        <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"
  >
    <UButton
        @click="showAddHistoryItemModal = true"
    >
      + Eintrag
    </UButton>
  </Toolbar>
  <div v-else>
    <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="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="dataStore.getProfileById(item.createdBy).fullName"
            v-else
        />
        <div>
          <h3 v-if="item.createdBy">{{dataStore.getProfileById(item.createdBy) ? dataStore.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>