<script setup lang="ts">
import { ref, onMounted } from 'vue';
import api from '@/utils/api';
import RoleList from '@/components/apps/setting/permission/RoleList.vue';
import RoleModal from '@/components/apps/setting/permission/RoleModal.vue';
import DialogConfrim from '~/components/shared/DialogConfrim.vue';
import LoadingState from '~/components/shared/LoadingState.vue';
import type { RoleMaster, RoleMasterListResponse } from '~/types/setting/roleMaster';
import { useSnackbarStore } from '~/store/snackbar';

const roles = ref<RoleMaster[]>([]);
const loading = ref(false);
const isModalOpen = ref(false);

const modalMode = ref<'create' | 'detail' | 'edit'>('create');
const selectedPageId = ref<number | null>(null);
const snackbarStore = useSnackbarStore();

const isDeleteDialogOpen = ref(false);
const isDeleting = ref(false);
const deleteTargetId = ref<number | null>(null);
const deleteTargetName = ref<string>('');


const fetchRoles = async () => {
  loading.value = true;
  try {
    const response = await api.get<RoleMasterListResponse>('/api/v1/roles/master');
    roles.value = response.data?.data ?? [];
  } catch (error) {
    snackbarStore.showSnackbar('Gagal memuat data roles', 'error');
  } finally {
    loading.value = false;
  }
};

const handlePageSaved = async () => {
  await fetchRoles();
};

const openCreateModal = () => {
  modalMode.value = 'create';
  selectedPageId.value = null;
  isModalOpen.value = true;
};

const openDetailModal = (page: RoleMaster) => {
  modalMode.value = 'detail';
  selectedPageId.value = page.id;
  isModalOpen.value = true;
};

const openEditRoleModal = (page: RoleMaster) => {
  modalMode.value = 'edit';
  selectedPageId.value = page.id;
  isModalOpen.value = true;
};

const openAssignPermission = (page: RoleMaster) => {
  navigateTo(`/apps/setting/permission/${page.id}`);
};

const openDeleteDialog = (page: RoleMaster) => {
  deleteTargetId.value = page.id;
  deleteTargetName.value = page.name;
  isDeleteDialogOpen.value = true;
};

const handleCancelDelete = () => {
  deleteTargetId.value = null;
  deleteTargetName.value = '';
};

const handleConfirmDelete = async () => {
  if (!deleteTargetId.value) return;
  if (isDeleting.value) return;

  isDeleting.value = true;
  try {
    await api.delete(`/api/v1/roles/master/${deleteTargetId.value}`);
    snackbarStore.showSnackbar('Role berhasil dihapus', 'success');
    isDeleteDialogOpen.value = false;
    await fetchRoles();
  } catch (error: any) {
    const message = error?.response?.data?.message || error?.message || 'Gagal menghapus role';
    snackbarStore.showSnackbar(message, 'error');
  } finally {
    isDeleting.value = false;
  }
};


onMounted(() => {
  fetchRoles();
});

definePageMeta({
  middleware: 'auth',
});
</script>

<template>
    <v-card elevation="0" class="mb-5">
        <v-card-title class="pa-4">
            <div class="d-flex align-center">
                <div>
                    <h4 class="text-h4">Role Permission</h4>
                </div>
                <v-spacer></v-spacer>
                <v-btn color="primary" flat @click="openCreateModal">
                    <v-icon class="mr-2">mdi-plus</v-icon>
                    Tambah Role
                </v-btn>
            </div>
        </v-card-title>
    </v-card>
    
      <LoadingState :loading="loading" :empty="roles.length === 0 && !loading" loading-text="Memuat data roles..."
        empty-text="Data Kosong">
        <div>
          <RoleList
            v-for="role in roles"
            :key="role.id"
            :role="role"
            @detail="openDetailModal"
            @edit-role="openEditRoleModal"
            @delete-role="openDeleteDialog"
            @assign-permission="openAssignPermission"
          />
        </div>
      </LoadingState>

    <DialogConfrim
      v-model="isDeleteDialogOpen"
      title="Hapus role"
      :message="`Apakah anda yakin menghapus role  ${deleteTargetName} ?`"
      :loading="isDeleting"
      :close-on-confirm="false"
      @confirm="handleConfirmDelete"
      @cancel="handleCancelDelete"
    />

    <RoleModal
      v-model="isModalOpen"
      :mode="modalMode"
      :role-id="selectedPageId"
      @saved="handlePageSaved"
    />
</template>
