<template>
  <div id="main">
    <UButton @click="showCreateProject = true">+ Projekt</UButton>
    <UModal v-model="showCreateProject">
      <UCard>
        <template #header>
          Projekt erstellen
        </template>

        <UFormGroup
            label="Name:"
        >
          <UInput
              v-model="createProjectData.name"
          />
        </UFormGroup>
        <UFormGroup
            label="Kunde:"
        >
          <USelectMenu
              v-model="createProjectData.customer"
              :options="dataStore.customers"
              option-attribute="name"
              value-attribute="id"
              searchable
              :search-attributes="['name']"
          />
        </UFormGroup>
        <UFormGroup
            label="Notizen:"
        >
          <UTextarea
              v-model="createProjectData.notes"
          />
        </UFormGroup>

        <template #footer>
          <UButton
              @click="createProject"
          >
            Erstellen
          </UButton>
        </template>
      </UCard>
    </UModal>
    <!-- TODO: USelect im Modal anpassen -->
    <UTable
        :rows="dataStore.projects"
        :columns="projectColumns"
        @select="selectProject"

    >
      <template #customer-data="{row}">
        {{dataStore.customers.find(customer => customer.id == row.customer ) ? dataStore.customers.find(customer => customer.id == row.customer ).name : row.id}}
      </template>


    </UTable>
  </div>

</template>

<script setup>

definePageMeta({
  middleware: "auth"
})

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

const projectColumns = [
  {
    key: 'measure',
    label: "Gewerk",
    sortable: true
  },
  {
    key: 'name',
    label: "Name",
    sortable: true
  },
  {
    key: "customer",
    label: "Kundennummer",
    sortable: true
  },
  {
    key: "notes",
    label: "Notizen",
    sortable: true
  }
]

const selectProject = (project) => {
  router.push(`/projects/${project.id} `)
}

const showCreateProject = ref(false)
const createProjectData = ref({
  phases: []
})

let selectedItem = ref({})

const selectItem = (item) => {
  selectedItem.value = item
  console.log(item)
}

const createProject = async () => {
  const {data,error} = await supabase
      .from("projects")
      .insert([createProjectData.value])
      .select()

  if(error) console.log(error)

  showCreateProject.value = false
  createProjectData.value = {phases: []}
  dataStore.fetchProjects()


}

</script>

<style scoped>
/*#main {
  display: flex;
  flex-direction: row;
}
#left {
  width: 25vw;
}

#right {
  width: 60vw;
  padding-left: 3vw;
}*/
</style>