<template>
  <div class="container mx-auto py-6 space-y-6">
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-3xl font-bold">Role Management</h1>
        <p class="text-muted-foreground">
          Create custom roles and edit create/edit/delete permissions for assets, shots, and tasks
        </p>
      </div>
      <Button @click="openCreateDialog">
        <Plus class="w-4 h-4 mr-2" />
        Create Role
      </Button>
    </div>

    <Card>
      <CardContent class="p-0">
        <div v-if="isLoading" class="p-6 text-center text-muted-foreground">Loading roles...</div>
        <table v-else class="w-full text-sm">
          <thead>
            <tr class="border-b bg-muted/50">
              <th class="text-left font-medium p-3">Name</th>
              <th class="text-left font-medium p-3">Description</th>
              <th class="text-left font-medium p-3">Permissions</th>
              <th class="text-left font-medium p-3">Users</th>
              <th class="text-right font-medium p-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="role in roles" :key="role.id" class="border-b last:border-b-0">
              <td class="p-3 font-medium">
                {{ role.name }}
                <Badge :variant="role.is_system ? 'secondary' : 'outline'" class="ml-2">
                  {{ role.is_system ? 'System' : 'Custom' }}
                </Badge>
              </td>
              <td class="p-3 text-muted-foreground">{{ role.description || '—' }}</td>
              <td class="p-3">{{ role.permissions.length }}</td>
              <td class="p-3">{{ role.user_count }}</td>
              <td class="p-3 text-right space-x-2">
                <Button variant="ghost" size="sm" @click="openEditDialog(role)">
                  <Pencil class="w-4 h-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  :disabled="role.is_system || role.user_count > 0"
                  :title="role.is_system ? 'System roles cannot be deleted' : role.user_count > 0 ? 'Reassign users before deleting' : 'Delete role'"
                  @click="confirmDelete(role)"
                >
                  <Trash2 class="w-4 h-4" />
                </Button>
              </td>
            </tr>
          </tbody>
        </table>
      </CardContent>
    </Card>

    <RoleFormDialog
      v-model:open="showFormDialog"
      :role="editingRole"
      :permissions="permissions"
      :saving="isSaving"
      @saved="handleSave"
    />

    <AlertDialog :open="showDeleteDialog" @update:open="(val: boolean) => { showDeleteDialog = val }">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete role "{{ roleToDelete?.name }}"?</AlertDialogTitle>
          <AlertDialogDescription>This cannot be undone.</AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction @click="handleDelete">Delete</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Plus, Pencil, Trash2 } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import {
  AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogTitle,
  AlertDialogDescription, AlertDialogFooter, AlertDialogCancel, AlertDialogAction
} from '@/components/ui/alert-dialog'
import { useToast } from '@/components/ui/toast/use-toast'
import { useRolesStore } from '@/stores/roles'
import RoleFormDialog from '@/components/role/RoleFormDialog.vue'
import type { Role } from '@/services/role'

const { toast } = useToast()
const rolesStore = useRolesStore()

const isLoading = ref(true)
const isSaving = ref(false)
const showFormDialog = ref(false)
const editingRole = ref<Role | null>(null)
const showDeleteDialog = ref(false)
const roleToDelete = ref<Role | null>(null)

const roles = computed(() => rolesStore.roles ?? [])
const permissions = computed(() => rolesStore.permissions ?? [])

onMounted(async () => {
  try {
    await Promise.all([rolesStore.fetchRoles(), rolesStore.fetchPermissions()])
  } catch (err: any) {
    toast({ title: 'Error', description: err.response?.data?.detail || 'Failed to load roles', variant: 'destructive' })
  } finally {
    isLoading.value = false
  }
})

function openCreateDialog() {
  editingRole.value = null
  showFormDialog.value = true
}

function openEditDialog(role: Role) {
  editingRole.value = role
  showFormDialog.value = true
}

async function handleSave(data: { name?: string; description?: string; permission_ids: number[] }) {
  isSaving.value = true
  try {
    if (editingRole.value) {
      await rolesStore.updateRole(editingRole.value.id, data)
      toast({ title: 'Role updated', description: `"${editingRole.value.name}" was updated.` })
    } else {
      const role = await rolesStore.createRole({ name: data.name!, description: data.description, permission_ids: data.permission_ids })
      toast({ title: 'Role created', description: `"${role.name}" was created.` })
    }
    showFormDialog.value = false
  } catch (err: any) {
    toast({ title: 'Error', description: err.response?.data?.detail || 'Failed to save role', variant: 'destructive' })
  } finally {
    isSaving.value = false
  }
}

function confirmDelete(role: Role) {
  roleToDelete.value = role
  showDeleteDialog.value = true
}

async function handleDelete() {
  // Captured locally: AlertDialogAction closes the dialog (and fires @update:open)
  // as part of the same click, so showDeleteDialog can't be trusted to still
  // reflect "open" by the time this runs - roleToDelete is never reset by that
  // close, only here, so it's safe to read.
  const role = roleToDelete.value
  if (!role) return
  try {
    await rolesStore.deleteRole(role.id)
    toast({ title: 'Role deleted', description: `"${role.name}" was deleted.` })
  } catch (err: any) {
    toast({ title: 'Error', description: err.response?.data?.detail || 'Failed to delete role', variant: 'destructive' })
  } finally {
    showDeleteDialog.value = false
    roleToDelete.value = null
  }
}
</script>
