<script setup>

const dataStore = useDataStore()
const supabase = useSupabaseClient()

const profiles = ref([])

const itemInfo = ref({})
const selectedProfiles = ref([])

const setup = async () => {
  profiles.value = await useSupabaseSelect("profiles")
  selectedProfiles.value = [dataStore.activeProfile.id]
}

setup()

const createChat = async () => {
  const {data,error} = await supabase.from("chats").insert({
    tenant: dataStore.currentTenant,
    name: itemInfo.value.name
  }).select()

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

    let memberships = selectedProfiles.value.map(i => {
      return {
        profile_id: i,
        chat_id: data[0].id
      }
    })

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

    if(error) {
      console.log(error)
    } else {
      navigateTo("/chats")
    }

  }

}

</script>

<template>
  <UDashboardNavbar>
    <template #left>
      <UButton
          icon="i-heroicons-chevron-left"
          variant="outline"
          @click="navigateTo(`/chats`)"
      >
        Chats
      </UButton>
    </template>
    <template #center>
      <h1
          v-if="itemInfo"
          class="text-xl font-medium"
      >Chat Erstellen</h1>
    </template>
    <template #right>
      <UButton
          @click="createChat"
      >
        Erstellen
      </UButton>
      <UButton
          @click="navigateTo(`/chats`)"
          color="red"
          class="ml-2"
      >
        Abbrechen
      </UButton>
    </template>
  </UDashboardNavbar>
  <UDashboardPanelContent>
    <UForm>
      <UFormGroup
          label="Name:"
      >
        <UInput
            v-model="itemInfo.name"
        />
      </UFormGroup>




      <UFormGroup
          label="Beteiligte Benutzer:"
      >
        <USelectMenu
            v-model="selectedProfiles"
            :options="profiles"
            option-attribute="fullName"
            value-attribute="id"
            searchable
            multiple
            :search-attributes="['fullName']"
        >
          <template #label>
            {{selectedProfiles.length > 0 ? selectedProfiles.map(i => dataStore.getProfileById(i).fullName).join(", ") : "Keine Benutzer ausgewählt"}}
          </template>
        </USelectMenu>
      </UFormGroup>
    </UForm>
  </UDashboardPanelContent>

</template>

<style scoped>

</style>