<script lang="ts" setup>
import { computed } from 'vue'
import {
  AccordionRoot,
  AccordionItem,
  AccordionTrigger,
  AccordionContent,
} from '@/components/ui/accordion'
import { CheckboxRoot, CheckboxControl, CheckboxLabel } from '@/components/ui/checkbox'
import {
  groupPermissionsByRoute,
  resolveDefaultOpenGroups,
} from '../utils/groupPermissions'
import type { RolePermission } from '../types/role.types'

const props = defineProps<{
  permissions: RolePermission[]
  selectedPermissionIds: Set<string>
  loading?: boolean
  disabled?: boolean
}>()

const emit = defineEmits<{
  checkedChange: [permissionId: string, checked: boolean]
}>()

const permissionGroups = computed(() => groupPermissionsByRoute(props.permissions))

const defaultOpenGroups = computed(() =>
  resolveDefaultOpenGroups(permissionGroups.value, props.selectedPermissionIds),
)

const accordionKey = computed(
  () =>
    `${permissionGroups.value.map((group) => group.key).join('|')}:${props.selectedPermissionIds.size}`,
)

function setPermissionChecked(permissionId: string, checked: boolean) {
  emit('checkedChange', permissionId, checked)
}
</script>

<template>
  <div class="max-h-96 overflow-auto rounded-lg border border-foreground/10 p-3">
    <div v-if="!permissions.length && !loading" class="py-6 text-center opacity-70">
      Tiada permissions ditemui
    </div>

    <AccordionRoot v-else-if="permissionGroups.length" :key="accordionKey" class="w-full"
      :default-value="defaultOpenGroups">
      <AccordionItem v-for="group in permissionGroups" :key="group.key" :value="group.key">
        <AccordionTrigger>{{ group.label }}</AccordionTrigger>
        <AccordionContent>
          <div class="grid grid-cols-1 gap-2 md:grid-cols-2">
            <CheckboxRoot v-for="permission in group.permissions" :key="permission.id"
              :checked="selectedPermissionIds.has(permission.id)" :disabled="loading || disabled"
              @checked-change="({ checked }) => setPermissionChecked(permission.id, checked === true)">
              <CheckboxControl />
              <CheckboxLabel>
                <span class="font-medium">{{ permission.name }}</span>
              </CheckboxLabel>
            </CheckboxRoot>
          </div>
        </AccordionContent>
      </AccordionItem>
    </AccordionRoot>
  </div>
</template>
