<script setup>
import { ref, computed, onMounted } from 'vue';
import { useAsnafMockData } from '~/composables/useAsnafMockData';

definePageMeta({
  title: "Senarai Asnaf",
  middleware: ["auth"],
  requiresAuth: true,
  breadcrumb: [
    {
      name: "Dashboard",
      path: "/",
    },
    {
      name: "BF-PRF",
      path: "/BF-PRF",
    },
    {
      name: "Asnaf",
      path: "/BF-PRF/AS",
    },
    {
      name: "Senarai",
      path: "/BF-PRF/AS/LIST",
    },
  ],
});

// Get asnaf data from the composable
const { asnafProfiles, statistics, filterProfiles, categories, statuses } = useAsnafMockData();

// Table reactivity control
const tableKey = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const totalProfiles = ref(0);
const isLoading = ref(false);

// Search and filter variables
const searchQuery = ref('');
const selectedStatus = ref('All');
const selectedCategory = ref('All');

// Table data and fields
const tableData = computed(() => {
  return filterProfiles(searchQuery.value, selectedStatus.value, selectedCategory.value);
});

const tableFields = [
  { field: 'no', label: 'No.' },
  { field: 'id', label: 'ID' },
  { field: 'nama', label: 'Nama' },
  { field: 'idNumber', label: 'No. ID' },
  { field: 'kategori', label: 'Kategori' },
  { field: 'status', label: 'Status' },
  { field: 'tindakan', label: 'Tindakan' }
];

// Generate table field and data mapping
const formattedTableData = computed(() => {
  return tableData.value.map((profile, index) => ({
    no: index + 1,
    id: profile.id,
    nama: profile.nama,
    idNumber: profile.idNumber,
    kategori: profile.kategori,
    status: profile.status,
    tindakan: profile.id
  }));
});

// Helper functions
function getBadgeVariantForCategory(category) {
  switch (category) {
    case 'Fakir': return 'danger';
    case 'Miskin': return 'warning';
    case 'Mualaf': return 'info';
    case 'Fi-sabilillah': return 'primary';
    case 'Gharimin': return 'secondary';
    case 'Ibnu Sabil': return 'success';
    default: return 'primary';
  }
}

function getBadgeVariantForStatus(status) {
  switch (status) {
    case 'Aktif': return 'success';
    case 'Tidak Aktif': return 'danger';
    case 'Dalam Semakan': return 'warning';
    default: return 'secondary';
  }
}

function navigateToDetail(id) {
  console.log("Attempting to navigate to detail for ID:", id);
  if (id) {
    navigateTo(`/BF-PRF/AS/DETAIL/${id}`);
  } else {
    console.error("Navigation failed: ID is undefined or null");
  }
}

function navigateToRegistration() {
  navigateTo('/BF-PRF/AS/FR/01');
}

// Pagination
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchProfiles();
};

// Fetch data
async function fetchProfiles() {
  isLoading.value = true;
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 500));
  
  totalProfiles.value = tableData.value.length;
  isLoading.value = false;
  tableKey.value++; // Force table re-render
}

// Lifecycle hooks
onMounted(() => {
  fetchProfiles();
});
</script>

<template>
  <div class="space-y-6">
    <LayoutsBreadcrumb />
    
    <!-- Header -->
    <div class="flex justify-between items-center">
      <h1 class="text-2xl font-bold text-primary">Senarai Asnaf</h1>
      <rs-button 
        variant="primary" 
        class="flex items-center gap-2"
        @click="navigateToRegistration"
      >
        <Icon name="mdi:plus" size="18" />
        <span>Tambah Asnaf</span>
      </rs-button>
    </div>
    
    <!-- Statistics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
      <rs-card class="transition-all duration-300 hover:shadow-lg">
        <div class="p-4 flex items-center gap-4">
          <div class="p-4 flex justify-center items-center bg-blue-100 rounded-xl">
            <Icon name="mdi:account-group" size="24" class="text-primary" />
          </div>
          <div>
            <span class="block text-2xl font-bold text-primary">{{ statistics.total }}</span>
            <span class="text-sm text-gray-600">Jumlah Asnaf</span>
          </div>
        </div>
      </rs-card>
      
      <rs-card class="transition-all duration-300 hover:shadow-lg">
        <div class="p-4 flex items-center gap-4">
          <div class="p-4 flex justify-center items-center bg-green-100 rounded-xl">
            <Icon name="mdi:check-circle" size="24" class="text-green-600" />
          </div>
          <div>
            <span class="block text-2xl font-bold text-green-600">{{ statistics.active }}</span>
            <span class="text-sm text-gray-600">Aktif</span>
          </div>
        </div>
      </rs-card>
      
      <rs-card class="transition-all duration-300 hover:shadow-lg">
        <div class="p-4 flex items-center gap-4">
          <div class="p-4 flex justify-center items-center bg-yellow-100 rounded-xl">
            <Icon name="mdi:clock-time-four" size="24" class="text-yellow-600" />
          </div>
          <div>
            <span class="block text-2xl font-bold text-yellow-600">{{ statistics.review }}</span>
            <span class="text-sm text-gray-600">Dalam Semakan</span>
          </div>
        </div>
      </rs-card>
      
      <rs-card class="transition-all duration-300 hover:shadow-lg">
        <div class="p-4 flex items-center gap-4">
          <div class="p-4 flex justify-center items-center bg-red-100 rounded-xl">
            <Icon name="mdi:close-circle" size="24" class="text-red-600" />
          </div>
          <div>
            <span class="block text-2xl font-bold text-red-600">{{ statistics.inactive }}</span>
            <span class="text-sm text-gray-600">Tidak Aktif</span>
          </div>
        </div>
      </rs-card>
    </div>
    
    <!-- Search and Filters -->
    <rs-card>
      <div class="p-4">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Carian</label>
            <div class="relative rounded-md shadow-sm">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Icon name="mdi:magnify" size="18" class="text-gray-400" />
              </div>
              <input
                v-model="searchQuery"
                type="text"
                class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
                placeholder="Cari dengan nama atau ID..."
              />
            </div>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
            <select
              v-model="selectedStatus"
              class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
            >
              <option value="All">Semua Status</option>
              <option v-for="status in statuses" :key="status" :value="status">
                {{ status }}
              </option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Kategori</label>
            <select
              v-model="selectedCategory"
              class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-primary focus:border-primary"
            >
              <option value="All">Semua Kategori</option>
              <option v-for="category in categories" :key="category" :value="category">
                {{ category }}
              </option>
            </select>
          </div>
        </div>
      </div>
    </rs-card>
    
    <!-- Data Table -->
    <rs-card>
      <template #header>
        <div class="px-4 py-3 flex items-center justify-between">
          <h2 class="text-lg font-semibold text-primary">Senarai Asnaf</h2>
          <span class="text-sm text-gray-500">
            {{ tableData.length }} asnaf dijumpai
          </span>
        </div>
      </template>
      
      <template #body>
        <div v-if="isLoading && tableData.length === 0" class="py-8 text-center">
          <div class="flex justify-center">
            <Icon name="mdi:loading" size="2rem" class="text-blue-500 animate-spin" />
          </div>
          <p class="mt-2 text-gray-600">Memuat data...</p>
        </div>
        
        <rs-table
          v-else
          class="mt-4"
          :key="tableKey"
          :data="formattedTableData"
          :columns="tableFields"
          :pageSize="pageSize"
          :showNoColumn="true"
          :options="{
            variant: 'default',
            hover: true,
            striped: true,
            bordered: true
          }"
          :current-page="currentPage"
          :total-items="totalProfiles"
          @page-change="handlePageChange"
        >
          <template v-slot:no="data">
            {{ data.text }}
          </template>

          <template v-slot:id="data">
            {{ data.text }}
          </template>

          <template v-slot:nama="data">
            <div class="font-medium">{{ data.text }}</div>
          </template>

          <template v-slot:idNumber="data">
            {{ data.text }}
          </template>

          <template v-slot:kategori="data">
            <rs-badge :variant="getBadgeVariantForCategory(data.text)">{{ data.text }}</rs-badge>
          </template>

          <template v-slot:status="data">
            <rs-badge :variant="getBadgeVariantForStatus(data.text)">
              {{ data.text }}
            </rs-badge>
          </template>

          <template v-slot:tindakan="data">
            <div class="flex gap-2">
              <rs-button
                variant="primary"
                size="sm"
                class="!px-2 !py-1"
                @click="() => { 
                  navigateToDetail(data.value.tindakan);
                }"
              >
                <Icon name="mdi:eye" size="1rem" class="mr-1" />
                Lihat
              </rs-button>
            </div>
          </template>
        </rs-table>

        <!-- Empty State -->
        <div v-if="!isLoading && tableData.length === 0" class="text-center py-8">
          <div class="flex justify-center mb-4">
            <Icon name="mdi:magnify" size="4rem" class="text-gray-400" />
          </div>
          <h3 class="text-lg font-medium text-gray-500">Tiada Profil Ditemui</h3>
          <p class="text-gray-500 mt-2">Sila cuba carian lain atau reset penapis.</p>
        </div>
      </template>
    </rs-card>
  </div>
</template> 