<script setup>
import { ref } from 'vue';
import { Button } from '@/components/ui';
import { useAuthentik } from '@/composables/useAuthentik.js';
import { useToast } from '@/composables/useToast.js';

const props = defineProps({
  groupName: {
    type: String,
    required: true
  },
  label: {
    type: String,
    default: 'Verificar Grupo'
  },
  icon: {
    type: String,
    default: null
  },
  verifyBackend: {
    type: Boolean,
    default: false
  }
});

const { hasGroup, checkGroupBackend } = useAuthentik();
const { toast } = useToast();
const loading = ref(false);

const handleClick = async () => {
  loading.value = true;

  try {
    if (props.verifyBackend) {
      const hasAccess = await checkGroupBackend(props.groupName);

      if (hasAccess) {
        toast.success('Acceso Permitido (Backend)', {
          description: `Perteneces al grupo: ${props.groupName}`,
        });
      } else {
        toast.error('Acceso Denegado (Backend)', {
          description: `No perteneces al grupo: ${props.groupName}`,
        });
      }
    } else {
      const hasAccess = hasGroup(props.groupName);

      if (hasAccess) {
        toast.success('Acceso Permitido (Frontend)', {
          description: `Perteneces al grupo: ${props.groupName}`,
        });
      } else {
        toast.error('Acceso Denegado (Frontend)', {
          description: `No perteneces al grupo: ${props.groupName}`,
        });
      }
    }
  } catch (error) {
    toast.error('Error de Verificación', {
      description: 'No se pudo verificar el grupo',
    });
    console.error('Group check error:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <Button
    :loading="loading"
    :disabled="loading"
    @click="handleClick"
  >
    <img v-if="icon" class="size-4 opacity-90" :src="icon" :alt="label" />
    <slot>{{ label }}</slot>
  </Button>
</template>
