<template>
  <div>
    <LayoutsBreadcrumb />

    <!-- Page Header -->
    <rs-card class="mb-6">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <Icon class="mr-2 text-primary" name="ic:outline-dashboard"></Icon>
            <h1 class="text-xl font-bold text-primary">Notification Dashboard</h1>
          </div>
          <rs-button size="sm" @click="refreshData">
            <Icon :name="isRefreshing ? 'ic:outline-refresh' : 'ic:outline-refresh'" :class="{ 'animate-spin': isRefreshing }" class="mr-1"></Icon>
            Refresh
          </rs-button>
        </div>
      </template>
      <template #body>
        <p class="text-gray-600">
          Overview of your notification system performance and statistics.
        </p>
      </template>
    </rs-card>

    <!-- Loading State -->
    <div v-if="isLoading" class="flex items-center justify-center py-12">
      <Icon name="ic:outline-refresh" class="text-primary animate-spin" size="32" />
    </div>

    <div v-else>
      <!-- Overview Stats Cards -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
        <!-- Total Notifications -->
        <rs-card class="transition-all duration-300 hover:shadow-lg">
          <div class="pt-5 pb-3 px-5 flex items-center gap-4">
            <div class="p-5 flex justify-center items-center rounded-2xl bg-blue-100">
              <Icon class="text-3xl text-blue-600" name="ic:outline-notifications"></Icon>
            </div>
            <div class="flex-1">
              <span class="block font-bold text-2xl text-blue-600">
                {{ overview.total || 0 }}
              </span>
              <span class="text-sm font-medium text-gray-600">Total Notifications</span>
            </div>
          </div>
        </rs-card>

        <!-- Sent Notifications -->
        <rs-card class="transition-all duration-300 hover:shadow-lg">
          <div class="pt-5 pb-3 px-5 flex items-center gap-4">
            <div class="p-5 flex justify-center items-center rounded-2xl bg-green-100">
              <Icon class="text-3xl text-green-600" name="ic:outline-send"></Icon>
            </div>
            <div class="flex-1">
              <span class="block font-bold text-2xl text-green-600">
                {{ overview.sent || 0 }}
              </span>
              <span class="text-sm font-medium text-gray-600">Sent</span>
              <div class="text-xs text-gray-500 mt-1">
                <span v-if="overview.growthRate > 0" class="text-green-600">
                  ↑ {{ overview.growthRate }}%
                </span>
                <span v-else-if="overview.growthRate < 0" class="text-red-600">
                  ↓ {{ Math.abs(overview.growthRate) }}%
                </span>
                <span v-else class="text-gray-600">→ 0%</span>
                vs last week
              </div>
            </div>
          </div>
        </rs-card>

        <!-- Scheduled Notifications -->
        <rs-card class="transition-all duration-300 hover:shadow-lg">
          <div class="pt-5 pb-3 px-5 flex items-center gap-4">
            <div class="p-5 flex justify-center items-center rounded-2xl bg-orange-100">
              <Icon class="text-3xl text-orange-600" name="ic:outline-schedule"></Icon>
            </div>
            <div class="flex-1">
              <span class="block font-bold text-2xl text-orange-600">
                {{ overview.scheduled || 0 }}
              </span>
              <span class="text-sm font-medium text-gray-600">Scheduled</span>
            </div>
          </div>
        </rs-card>

        <!-- Delivery Rate -->
        <rs-card class="transition-all duration-300 hover:shadow-lg">
          <div class="pt-5 pb-3 px-5 flex items-center gap-4">
            <div class="p-5 flex justify-center items-center rounded-2xl bg-purple-100">
              <Icon class="text-3xl text-purple-600" name="ic:outline-check-circle"></Icon>
            </div>
            <div class="flex-1">
              <span class="block font-bold text-2xl text-purple-600">
                {{ delivery.deliveryRate || 0 }}%
              </span>
              <span class="text-sm font-medium text-gray-600">Delivery Rate</span>
            </div>
          </div>
        </rs-card>
      </div>

      <!-- Delivery Stats Row -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
        <!-- Total Recipients -->
        <rs-card>
          <div class="pt-5 pb-3 px-5">
            <div class="flex items-center justify-between mb-2">
              <span class="text-gray-600 text-sm">Total Recipients</span>
              <Icon name="ic:outline-people" class="text-gray-400"></Icon>
            </div>
            <div class="flex items-baseline gap-2">
              <span class="text-2xl font-bold">{{ delivery.totalRecipients || 0 }}</span>
            </div>
          </div>
        </rs-card>

        <!-- Successful Deliveries -->
        <rs-card>
          <div class="pt-5 pb-3 px-5">
            <div class="flex items-center justify-between mb-2">
              <span class="text-gray-600 text-sm">Successful</span>
              <Icon name="ic:outline-check" class="text-green-500"></Icon>
            </div>
            <div class="flex items-baseline gap-2">
              <span class="text-2xl font-bold text-green-600">{{ delivery.successful || 0 }}</span>
            </div>
          </div>
        </rs-card>

        <!-- Failed Deliveries -->
        <rs-card>
          <div class="pt-5 pb-3 px-5">
            <div class="flex items-center justify-between mb-2">
              <span class="text-gray-600 text-sm">Failed</span>
              <Icon name="ic:outline-error" class="text-red-500"></Icon>
            </div>
            <div class="flex items-baseline gap-2">
              <span class="text-2xl font-bold text-red-600">{{ delivery.failed || 0 }}</span>
            </div>
          </div>
        </rs-card>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <!-- Channel Performance -->
        <rs-card>
          <template #header>
            <div class="flex items-center">
              <Icon class="mr-2 text-primary" name="ic:outline-bar-chart"></Icon>
              <h2 class="text-lg font-semibold text-primary">Channel Performance</h2>
            </div>
          </template>
          <template #body>
            <div v-if="channelPerformance.length === 0" class="text-center py-8 text-gray-500">
              No channel data available
            </div>
            <div v-else class="space-y-4">
              <div v-for="channel in channelPerformance" :key="channel.channel" class="border border-gray-200 rounded-lg p-4">
                <div class="flex items-center justify-between mb-3">
                  <div class="flex items-center gap-2">
                    <Icon :name="getChannelIcon(channel.channel)" class="text-xl"></Icon>
                    <span class="font-semibold capitalize">{{ channel.channel }}</span>
                  </div>
                  <rs-badge :variant="channel.successRate >= 90 ? 'success' : channel.successRate >= 70 ? 'warning' : 'danger'" size="sm">
                    {{ channel.successRate }}% Success
                  </rs-badge>
                </div>
                <div class="grid grid-cols-3 gap-3 text-sm">
                  <div>
                    <div class="text-gray-600">Total</div>
                    <div class="font-semibold">{{ channel.totalSent }}</div>
                  </div>
                  <div>
                    <div class="text-gray-600">Successful</div>
                    <div class="font-semibold text-green-600">{{ channel.successful }}</div>
                  </div>
                  <div>
                    <div class="text-gray-600">Failed</div>
                    <div class="font-semibold text-red-600">{{ channel.failed }}</div>
                  </div>
                </div>
                <!-- Progress Bar -->
                <div class="mt-3">
                  <div class="w-full bg-gray-200 rounded-full h-2">
                    <div class="bg-green-500 h-2 rounded-full" :style="{ width: channel.successRate + '%' }"></div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </rs-card>

        <!-- Top Categories -->
        <rs-card>
          <template #header>
            <div class="flex items-center">
              <Icon class="mr-2 text-primary" name="ic:outline-category"></Icon>
              <h2 class="text-lg font-semibold text-primary">Top Categories</h2>
            </div>
          </template>
          <template #body>
            <div v-if="topCategories.length === 0" class="text-center py-8 text-gray-500">
              No category data available
            </div>
            <div v-else class="space-y-3">
              <div v-for="(cat, index) in topCategories" :key="cat.categoryId" class="flex items-center justify-between p-3 border border-gray-200 rounded-lg">
                <div class="flex items-center gap-3">
                  <div class="w-8 h-8 flex items-center justify-center rounded-full bg-primary text-white font-bold text-sm">
                    {{ index + 1 }}
                  </div>
                  <span class="font-medium">{{ cat.categoryName }}</span>
                </div>
                <rs-badge variant="primary">{{ cat.count }}</rs-badge>
              </div>
            </div>
          </template>
        </rs-card>
      </div>

      <!-- Recent Notifications -->
      <rs-card>
        <template #header>
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <Icon class="mr-2 text-primary" name="ic:outline-history"></Icon>
              <h2 class="text-lg font-semibold text-primary">Recent Notifications</h2>
            </div>
            <NuxtLink to="/notification/list">
              <rs-button size="sm" variant="outline">
                View All
              </rs-button>
            </NuxtLink>
          </div>
        </template>
        <template #body>
          <div v-if="recentNotifications.length === 0" class="text-center py-8 text-gray-500">
            No recent notifications
          </div>
          <div v-else class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead>
                <tr>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Title</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Category</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Channels</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Recipients</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Created</th>
                </tr>
              </thead>
              <tbody class="divide-y divide-gray-200">
                <tr v-for="notif in recentNotifications" :key="notif.id" class="hover:bg-gray-50">
                  <td class="px-4 py-3">
                    <NuxtLink :to="`/notification/view/${notif.id}`" class="text-primary hover:underline font-medium">
                      {{ notif.title }}
                    </NuxtLink>
                  </td>
                  <td class="px-4 py-3">
                    <span class="text-sm">{{ notif.category }}</span>
                  </td>
                  <td class="px-4 py-3">
                    <div class="flex gap-1">
                      <Icon v-for="channel in notif.channels" :key="channel" :name="getChannelIcon(channel)" class="text-gray-600" size="18"></Icon>
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <rs-badge :variant="getStatusVariant(notif.status)" size="sm">
                      {{ notif.status }}
                    </rs-badge>
                  </td>
                  <td class="px-4 py-3">
                    <span class="text-sm">{{ notif.recipientCount }}</span>
                  </td>
                  <td class="px-4 py-3">
                    <span class="text-sm text-gray-600">{{ formatDate(notif.createdAt) }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </template>
      </rs-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

definePageMeta({
  title: 'Notification Dashboard',
  middleware: ['auth'],
  requiresAuth: true,
  breadcrumb: [
    {
      name: 'Notification',
      path: '/notification',
    },
    {
      name: 'Dashboard',
      path: '/notification/dashboard',
      type: 'current',
    },
  ],
});

const isLoading = ref(false);
const isRefreshing = ref(false);
const overview = ref({});
const delivery = ref({});
const channelPerformance = ref([]);
const topCategories = ref([]);
const recentNotifications = ref([]);

async function fetchDashboardData() {
  try {
    isLoading.value = true;

    const [overviewData, recentData, channelData] = await Promise.all([
      $fetch('/api/notifications/dashboard/overview'),
      $fetch('/api/notifications/dashboard/recent?limit=10'),
      $fetch('/api/notifications/dashboard/channel-performance'),
    ]);

    if (overviewData.success) {
      overview.value = overviewData.data.overview;
      delivery.value = overviewData.data.delivery;
      topCategories.value = overviewData.data.topCategories;
    }

    if (recentData.success) {
      recentNotifications.value = recentData.data;
    }

    if (channelData.success) {
      channelPerformance.value = channelData.data;
    }
  } catch (error) {
    console.error('Error fetching dashboard data:', error);
  } finally {
    isLoading.value = false;
  }
}

async function refreshData() {
  isRefreshing.value = true;
  await fetchDashboardData();
  isRefreshing.value = false;
}

function getChannelIcon(channel) {
  const icons = {
    email: 'ic:outline-email',
    push: 'ic:outline-notifications',
    sms: 'ic:outline-sms',
  };
  return icons[channel] || 'ic:outline-circle';
}

function getStatusVariant(status) {
  const variants = {
    draft: 'secondary',
    scheduled: 'warning',
    sending: 'primary',
    sent: 'success',
    failed: 'danger',
  };
  return variants[status] || 'secondary';
}

function formatDate(dateString) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
}

onMounted(() => {
  fetchDashboardData();

  // Auto-refresh every 60 seconds
  const interval = setInterval(fetchDashboardData, 60000);

  // Cleanup on unmount
  onUnmounted(() => clearInterval(interval));
});
</script>

<style lang="scss" scoped></style>
