<script setup lang="ts">
import { ref } from 'vue'
import {
  DropdownMenu, DropdownMenuItem,
  DropdownMenuTrigger, DropdownMenuContent
} from '@/components/ui/dropdown-menu'
import EditDeviceDialog from './EditDeviceDialog.vue'
import DeleteDeviceDialog from './DeleteDeviceDialog.vue'
import DeviceCertificateDialog from './DeviceCertificateDialog.vue'
import DeviceTasksDialog from './DeviceTasksDialog.vue'
import { Ellipsis } from 'lucide-vue-next'
import type { Device, Users } from '@/lib/interfaces'
// import { api } from '@/lib/api'


const props = defineProps<{ row: Device; allUsers?: Users[] }>()

const isEditOpen = ref(false)
const isDeleteOpen = ref(false)
const isTasksOpen = ref(false)
const itCertsOpen = ref(false)

const emit = defineEmits<{
  (e: 'updated', payload: { name: string; userIds: string[] }): void
  (e: 'deleted'): void
}>()

function onDeleteConfirmed() {
  // await api.delete(`/devices/${encodeURIComponent(props.row.guid)}`)
  isDeleteOpen.value = false
  emit('deleted')
}
function onEditConfirm(_payload: { name: string; userIds: string[] }) {
  isEditOpen.value = false
  emit('updated', _payload)
}

function onTaskConfirm() {
    isTasksOpen.value = false
}

function onCertsConfirm() {
    itCertsOpen.value = false
}
</script>

<template>
  <DropdownMenu>
    <DropdownMenuTrigger asChild>
      <button class="p-2 rounded hover:bg-muted">
        <Ellipsis />
      </button>
    </DropdownMenuTrigger>
    <DropdownMenuContent align="end" class="w-[160px]">
      <DropdownMenuItem @click.prevent="isEditOpen = true">Rename</DropdownMenuItem>
      <DropdownMenuItem @click.prevent="isTasksOpen = true">Tasks</DropdownMenuItem>
      <DropdownMenuItem @click.prevent="itCertsOpen = true">Certificates</DropdownMenuItem>
      <DropdownMenuItem class="text-destructive" @click.prevent="isDeleteOpen = true">Delete</DropdownMenuItem>
    </DropdownMenuContent>
  </DropdownMenu>

  <EditDeviceDialog v-model:modelValue="isEditOpen" :device="props.row" :all-users="props.allUsers" @updated="onEditConfirm" />
  <DeleteDeviceDialog v-model:modelValue="isDeleteOpen" :device="props.row" @confirm="onDeleteConfirmed" />
  <DeviceCertificateDialog v-model:modelValue="itCertsOpen" :device="props.row" @confirm="onCertsConfirm" />
  <DeviceTasksDialog v-model:modelValue="isTasksOpen" :device="props.row" @confirm="onTaskConfirm" />
</template>
