<template>
  <UPage>
    <!-- TODO: Benutzer Aufgaben zuweisen und nach diesen Filtern    -->
    <UModal
        v-model="showCreateTask"
    >
      <UCard>
        <template #header>
          Aufgabe erstellen
        </template>

        <UFormGroup
            label="Titel:"
            class="mt-2"
        >
          <UInput
              v-model="createTaskData.name"
          />
        </UFormGroup>

        <UFormGroup
            label="Beschreibung:"
            class="mt-2"
        >
          <UTextarea
              v-model="createTaskData.description"
          />
        </UFormGroup>

        <UFormGroup
            label="Kategorie:"
            class="mt-2"
        >
          <USelectMenu
              :options="taskCategories"
              v-model="createTaskData.categorie"
          />
        </UFormGroup>

        <UFormGroup
            label="Benutzer:"
            class="mt-2"
        >
          <USelectMenu
              :options="usersForList"
              v-model="createTaskData.users"
              multiple
          />
        </UFormGroup>


        <template #footer>
          <UButton
              @click="createTask"
          >
            Erstellen
          </UButton>
        </template>

      </UCard>
    </UModal>

    <UModal
        v-model="showTaskModal"
    >
      <UCard>
        <template #header>
          {{taskData.name}}
        </template>
        <p>{{taskData.description}}</p>
        <p>Erstellt am: {{taskData.created_at}}</p>
        <UBadge
            v-for="user in taskData.users"
            class="mr-2"
        >
          {{user}}
        </UBadge>
        <template #footer>
          <UFormGroup
            label="Status ändern:"
          >
            <USelectMenu
                :options="taskCategories"
                @change="updateTask"
                v-model="taskData.categorie"
            />
          </UFormGroup>

          <UFormGroup
            label="Benutzer ändern:"
          >
            <USelectMenu
                :options="profiles"
                @change="updateTask"
                v-model="taskData.user"
                option-attribute="firstName"
                value-attribute="id"
            >
              <template #label>
                {{profiles.find(profile => profile.id === taskData.user) ? profiles.find(profile => profile.id === taskData.user).firstName : 'Kein Benutzer ausgewählt'}}
              </template>
            </USelectMenu>
          </UFormGroup>

        </template>
      </UCard>
    </UModal>

    <div class="flex items-center gap-1">
      <UButton @click="showCreateTask = true">+ Aufgabe</UButton>

      <UInput
          v-model="searchString"
          placeholder="Suche..."
      />

      <UCheckbox
        label="Erledigte Anzeigen"
        v-model="showDoneTasks"
      />
    </div>

   <UTable
     :rows="filteredRows"
     :columns="taskColumns"
     @select="inspectTask"
   >
     <template #created_at-data="{row}">
       {{ dayjs(row.created_at).format("DD.MM.YY HH:mm") }}
     </template>
      <template #user-data="{row}">
        {{profiles.find(profile => profile.id === row.user ) ? profiles.find(profile => profile.id === row.user ).firstName : row.user}}
      </template>
   </UTable>




  </UPage>
</template>

<script setup>

import * as dayjs from "dayjs";

definePageMeta({
  middleware: "auth",
})

const toast = useToast()
const supabase = useSupabaseClient()
const {tasks, profiles} = storeToRefs(useDataStore())
const {fetchTasks} = useDataStore()

const taskColumns = [
  {
    key:"created_at",
    label: "Erstellt am:",
    sortable: true
  },
  {
    key:"name",
    label: "Name:",
    sortable: true
  },
  {
    key:"user",
    label: "Benutzer:",
    sortable: true
  },
  {
    key:"description",
    label: "Beschreibung:",
    sortable: true
  },
  {
    key:"categorie",
    label: "Kategorie:",
    sortable: true
  }
]

const showDoneTasks = ref(false)
const searchString = ref("")
const filteredRows = computed(() => {

  let filteredTasks = tasks.value.filter(task =>  !showDoneTasks.value ? task.categorie !== "Erledigt" : task.categorie === "Erledigt")

  if(!searchString.value) {
    return filteredTasks
  }

  return filteredTasks.filter(item => {
    return Object.values(item).some((value) => {
      return String(value).toLowerCase().includes(searchString.value.toLowerCase())
    })
  })
})


const showCreateTask = ref(false)
const taskCategories = ["Offen","In Bearbeitung", "Dringend","Erledigt"]

const createTaskData = ref({
  name: "",
  description: "",
  categorie: "Offen",
  user: ""
  /*users: ["86e67794-0ea8-41b0-985a-1072e84f56e9"]*/
})

const taskData = ref({})
const showTaskModal = ref(false)

const createTask = async () => {
  //await create('tasks', createTaskData.value)
  const {data,error} = await supabase
      .from("tasks")
      .insert([createTaskData.value])
      .select()

  console.log(error)

  showCreateTask.value = false
  createTaskData.value = {}
  fetchTasks()
}

const updateTask = async () => {

  console.log(taskData.value)
  const {data,error} = await supabase
      .from("tasks")
      .update(taskData.value)
      .eq('id',taskData.value.id)
      .select()
  console.log(data)

  if(error) {
    console.log(error)
  } else {
    toast.add({title: "Aufgabe aktualisiert"})
    taskData.value = {}
    showTaskModal.value = false
    fetchTasks()
  }

}

const inspectTask = (task) => {
  taskData.value = task
  showTaskModal.value = true
}

</script>

<style scoped>

#main {

}

h3 {
  font-size: large;
  font-weight: bold;
}

#menuBar {
  display: flex;
  flex-direction: row;
}

#taskCatList {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 65vh;
}

.taskScrollList {
  height: 60vh;
  overflow: auto;
  padding: 3px
}

#catNew {
  width: 30%;
}
#catInProgress {
  width: 30%;
  border-left: 2px solid #69c350;
  margin-left: 1em;
  padding-left: 1em;

}
#catUrgent {
  width: 30%;
  border-left: 2px solid #69c350;
  margin-left: 1em;
  padding-left: 1em;
}
</style>