<template>
  <Dialog :open="open" @update:open="$emit('update:open', $event)">
    <DialogContent class="sm:max-w-sm">
      <DialogHeader>
        <DialogTitle>Manage Roles</DialogTitle>
        <DialogDescription>
          {{ user ? `${user.first_name} ${user.last_name}` : '' }} — assign custom roles in addition to their base role
        </DialogDescription>
      </DialogHeader>

      <div class="space-y-2 max-h-72 overflow-auto">
        <label
          v-for="role in roles"
          :key="role.id"
          class="flex items-center gap-2 rounded-md p-2 hover:bg-accent cursor-pointer"
        >
          <Checkbox
            :model-value="selectedRoleIds.has(role.id)"
            @update:model-value="(val) => toggleRole(role.id, !!val)"
          />
          <span class="flex-1">{{ role.name }}</span>
          <Badge :variant="role.is_system ? 'secondary' : 'outline'">{{ role.is_system ? 'System' : 'Custom' }}</Badge>
        </label>
        <p v-if="roles.length === 0" class="text-sm text-muted-foreground p-2">No roles available.</p>
      </div>

      <DialogFooter>
        <Button type="button" variant="outline" @click="$emit('update:open', false)">Cancel</Button>
        <Button :disabled="saving" @click="handleSave">{{ saving ? 'Saving...' : 'Save' }}</Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Badge } from '@/components/ui/badge'
import type { Role } from '@/services/role'
import type { User } from '@/types/auth'

interface Props {
  open: boolean
  user: User | null
  roles: Role[]
  saving?: boolean
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:open': [value: boolean]
  saved: [roleIds: number[]]
}>()

const selectedRoleIds = ref<Set<number>>(new Set())

watch(() => props.open, (isOpen) => {
  if (!isOpen) return
  selectedRoleIds.value = new Set(props.user?.roles?.map(r => r.id) ?? [])
})

function toggleRole(id: number, checked: boolean) {
  if (checked) selectedRoleIds.value.add(id)
  else selectedRoleIds.value.delete(id)
}

function handleSave() {
  emit('saved', [...selectedRoleIds.value])
}
</script>
