<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useProjectsStore } from '@/stores/projects.ts'
import { storeToRefs } from 'pinia'
import DynamicMenu from '@/components/DynamicMenu.vue'
import type { DynamicMenuElement, TableHeader } from '@/types.ts'
import ProjectCreateFlow from '@/components/ProjectCreateFlow.vue'

const projectsStore = useProjectsStore()
const { projects } = storeToRefs(projectsStore)

const headers: TableHeader[] = [
  { title: 'Name', key: 'name', width: 400 },
  { title: 'Key', key: 'key' },
  { title: 'Actions', key: 'actions', width: 100, align: 'end', sortable: false },
]

const menu: DynamicMenuElement[] = [
  {
    id: 1,
    title: 'settings',
    icon: 'mdi-cog',
    click: projectSettings,
  },
  {
    id: 2,
    type: 'divider',
  },
  {
    id: 3,
    title: 'delete',
    icon: 'mdi-trash-can',
    color: 'error',
    click: deleteProject,
  },
]

const dialog = ref(false)

function projectSettings(id?: number) {
  console.log('d', id)
}

async function deleteProject(id?: number) {
  console.log('p', id)
  if (id) await projectsStore.remove(id)
}

onMounted(async () => {})
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-4">
      <div class="text-h5 font-weight-bold">Projects</div>

      <v-dialog transition="dialog-bottom-transition" max-width="500" v-model="dialog">
        <template v-slot:activator="{ props: activatorProps }">
          <v-btn v-bind="activatorProps" density="comfortable">
            <span class="text-body-2">Create project</span>
          </v-btn>
        </template>
        <project-create-flow v-model:dialog="dialog"></project-create-flow>
      </v-dialog>
    </div>
    <div class="d-flex ga-4 w-100 w-md-25">
      <v-text-field :disabled="true" prepend-inner-icon="mdi-magnify" placeholder="search projects"></v-text-field>
    </div>
    <v-data-table :headers hover hide-default-footer class="border rounded" density="compact" :items="projects">
      <template #[`item.name`]="{ item }">
        <div class="d-flex ga-2">
          <v-avatar color="blue" border rounded size="25"></v-avatar>
          <v-hover v-slot="{ isHovering, props }">
            <router-link
              v-bind="props"
              class="text-primary text-body-1 text-blue"
              :class="{ 'text-decoration-none': !isHovering }"
              :to="`/projects/${item.key}/issues`"
            >
              {{ item.name }}
            </router-link>
          </v-hover>
        </div>
      </template>
      <template #[`item.actions`]="{ item }">
        <span>{{ item.id }}</span>
        <dynamic-menu :menu :item-id="item.id"></dynamic-menu>
      </template>
    </v-data-table>
  </div>
</template>

<style scoped lang="scss"></style>
