<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import api from '@/utils/api';
import PageRow from '@/components/apps/setting/pages/PageRow.vue';
import AddPageModal from '@/components/apps/setting/pages/AddPageModal.vue';
import DialogConfrim from '~/components/shared/DialogConfrim.vue';
import LoadingState from '~/components/shared/LoadingState.vue';
import type { RolePage } from '~/types/setting/menu';
import { useSnackbarStore } from '~/store/snackbar';

const pages = ref<RolePage[]>([]);
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 activeFilter = ref<'Aktif' | boolean>(true);
const activeFilterItems: Array<{ title: string; value: '' | boolean }> = [
  { title: 'Semua', value: '' },
  { title: 'Aktif', value: true },
  { title: 'Tidak Aktif', value: false },
];


const fetchPages = async () => {
  loading.value = true;
  try {
    const response = await api.get('/api/v1/roles/pages/tree', {
      params: {
        active: activeFilter.value,
      },
    });
    pages.value = response.data?.data || [];
  } catch (error) {
    snackbarStore.showSnackbar('Gagal memuat data menu', 'error');
  } finally {
    loading.value = false;
  }
};

watch(activeFilter, () => {
  fetchPages();
});

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

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

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

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

const openDeleteDialog = (page: RolePage) => {
  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/pages/${deleteTargetId.value}`);
    snackbarStore.showSnackbar('Menu berhasil dihapus', 'success');
    isDeleteDialogOpen.value = false;
    await fetchPages();
  } catch (error: any) {
    const message = error?.response?.data?.message || error?.message || 'Gagal menghapus menu';
    snackbarStore.showSnackbar(message, 'error');
  } finally {
    isDeleting.value = false;
  }
};


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

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">Menu</h4>
                </div>
                <v-spacer></v-spacer>
                <v-select
                  v-model="activeFilter"
                  :items="activeFilterItems"
                  item-title="title"
                  item-value="value"
                  variant="outlined"
                  density="compact"
                  hide-details
                  class="me-3"
                  style="max-width: 200px"
                  placeholder="Filter status"
                />
                <v-btn color="primary" flat @click="openCreateModal">
                    <v-icon class="mr-2">mdi-plus</v-icon>
                    Tambah Menu
                </v-btn>
            </div>
        </v-card-title>
    </v-card>
    
      <LoadingState :loading="loading" :empty="pages.length === 0 && !loading" loading-text="Memuat data pages..."
        empty-text="Tidak ada data pages">
        <div>
          <PageRow
            v-for="page in pages"
            :key="page.id"
            :page="page"
            :level="0"
            @detail="openDetailModal"
            @edit="openEditModal"
            @delete="openDeleteDialog"
          />
        </div>
      </LoadingState>
    <AddPageModal v-model="isModalOpen" :mode="modalMode" :page-id="selectedPageId" @saved="handlePageSaved" />

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