<script setup lang="ts">
import { ref, onMounted } from 'vue';
import api from '@/utils/api';
import { Icon } from "@iconify/vue";


interface RolePage {
  id: number;
  name: string;
  icon: string;
  url: string;
  level: number;
  sort: number;
  active: boolean;
  children?: RolePage[];
}

const pages = ref<RolePage[]>([]);
const loading = ref(false);

const fetchPages = async () => {
  loading.value = true;
  try {
    const response = await api.get('/api/v1/roles/pages/tree');
    pages.value = response.data?.data || [];
    console.log('Pages loaded:', pages.value);
  } catch (error) {
    console.error('Error fetching pages:', error);
  } finally {
    loading.value = false;
  }
};

const handleStatusChange = (page: RolePage) => {
  console.log(`Page ${page.name} status changed to: ${page.active}`);
  // Here you can add the API call to update the status on the server
  // For example:
  // api.put(`/api/v1/roles/pages/${page.id}`, { active: page.active })
  //   .catch(error => console.error('Error updating status:', error));
};

onMounted(() => {
  fetchPages();
});
</script>

<template>
  <div v-if="loading" class="text-center py-4">
    <v-progress-circular indeterminate color="primary"></v-progress-circular>
  </div>

  <div v-else-if="pages.length === 0" class="text-center py-4">
    <p class="text-muted">No pages found</p>
  </div>

  <div v-else>
      <v-card v-for="page in pages" :key="page.id" class="mb-2" elevation="10">
        <v-card-text class="px-4 pb-0 pt-4">
          <div class="d-flex align-top">
            <Icon :icon="'solar:' + page.icon" width="18" />
            <div class="flex-grow-1 ms-2">
              <h4 class="mb-1">{{ page.name }}</h4>
              <p class="text-muted mb-0">{{ page.url }}</p>
            </div>
            <v-switch v-model="page.active" @change="handleStatusChange(page)"></v-switch>
          </div>
        </v-card-text>
      </v-card>
  </div>
</template>
