<template>
  <div>
    <LayoutsBreadcrumb />

    <!-- Info Card -->
    <rs-card class="mb-5">
      <template #header>
        <div class="flex">
          <Icon class="mr-2 flex justify-center" name="ic:outline-info"></Icon>
          Notification Details
        </div>
      </template>
      <template #body>
        <p class="mb-4">
          View detailed information about this notification including content, delivery
          settings, performance metrics, and recipient targeting.
        </p>
      </template>
    </rs-card>

    <!-- Loading State -->
    <div v-if="isLoading" class="text-center py-12">
      <div class="flex justify-center mb-4">
        <Icon name="ic:outline-refresh" size="2rem" class="text-primary animate-spin" />
      </div>
      <p class="text-gray-600">Loading notification details...</p>
    </div>

    <!-- Notification Not Found -->
    <rs-card v-else-if="!notification">
      <template #body>
        <div class="text-center py-8">
          <div class="flex justify-center mb-4">
            <Icon name="ic:outline-error" size="4rem" class="text-red-400" />
          </div>
          <h3 class="text-lg font-medium text-gray-500 mb-2">Notification Not Found</h3>
          <p class="text-gray-500 mb-4">
            The notification you're looking for doesn't exist or has been deleted.
          </p>
          <rs-button @click="$router.push('/notification/list')" variant="primary">
            <Icon name="ic:outline-arrow-back" class="mr-1"></Icon>
            Back to List
          </rs-button>
        </div>
      </template>
    </rs-card>

    <!-- Notification Details -->
    <div v-else class="space-y-6">
      <!-- Header Actions -->
      <rs-card>
        <template #body>
          <div class="flex justify-between items-center">
            <div class="flex items-center gap-4">
              <Icon name="ic:outline-notifications" class="text-primary" size="32" />
              <div>
                <h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                  {{ notification.title }}
                </h1>
                <div class="flex items-center gap-2 mt-1">
                  <rs-badge :variant="getStatusVariant(notification.status)">
                    {{ notification.status }}
                  </rs-badge>
                  <rs-badge :variant="getPriorityVariant(notification.priority)">
                    {{ notification.priority }} Priority
                  </rs-badge>
                </div>
              </div>
            </div>
            <div class="flex gap-3">
              <rs-button @click="$router.push('/notification/list')" variant="primary">
                <Icon name="ic:outline-arrow-back" class="mr-1"></Icon>
                Back to List
              </rs-button>
              <rs-button
                @click="editNotification"
                v-if="
                  notification.status === 'draft' || notification.status === 'scheduled'
                "
              >
                <Icon name="material-symbols:edit" class="mr-1"></Icon>
                Edit
              </rs-button>
            </div>
          </div>
        </template>
      </rs-card>

      <!-- Basic Information -->
      <rs-card>
        <template #header>
          <h2 class="text-xl font-semibold">Basic Information</h2>
        </template>
        <template #body>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Title</label
              >
              <p class="text-base text-gray-900 dark:text-gray-100">
                {{ notification.title }}
              </p>
            </div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Category</label
              >
              <p class="text-base text-gray-900 dark:text-gray-100">
                {{ notification.category.name }}
              </p>
            </div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Priority</label
              >
              <rs-badge :variant="getPriorityVariant(notification.priority)">
                {{ notification.priority }}
              </rs-badge>
            </div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Status</label
              >
              <rs-badge :variant="getStatusVariant(notification.status)">
                {{ notification.status }}
              </rs-badge>
            </div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Delivery Type</label
              >
              <p class="text-base text-gray-900 dark:text-gray-100 capitalize">
                {{ notification.deliveryType }}
              </p>
            </div>
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Recipients</label
              >
              <p class="text-base text-gray-900 dark:text-gray-100">
                {{ formatNumber(notification.analytics.totalRecipients) }}
              </p>
            </div>
          </div>
        </template>
      </rs-card>

      <!-- Delivery Channels -->
      <rs-card>
        <template #header>
          <h2 class="text-xl font-semibold">Delivery Channels</h2>
        </template>
        <template #body>
          <div class="flex flex-wrap gap-4">
            <div
              v-for="channel in notification.channels"
              :key="channel"
              class="flex items-center gap-2 p-3 border rounded-lg bg-gray-50 dark:bg-gray-800"
            >
              <Icon :name="getChannelIcon(channel)" size="20" class="text-primary" />
              <span class="font-medium capitalize">{{ channel }}</span>
            </div>
          </div>
        </template>
      </rs-card>

      <!-- Performance Metrics -->
      <rs-card v-if="notification.status === 'sent' || notification.status === 'sending'">
        <template #header>
          <h2 class="text-xl font-semibold">Performance Metrics</h2>
        </template>
        <template #body>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div class="text-center p-4 border rounded-lg">
              <div class="text-2xl font-bold text-green-600">
                {{ formatNumber(notification.analytics.deliveredCount) }}
              </div>
              <div class="text-sm text-gray-600">Successfully Delivered</div>
            </div>
            <div class="text-center p-4 border rounded-lg">
              <div class="text-2xl font-bold text-red-600">
                {{ formatNumber(notification.analytics.failedCount) }}
              </div>
              <div class="text-sm text-gray-600">Failed</div>
            </div>
            <div class="text-center p-4 border rounded-lg">
              <div class="text-2xl font-bold text-primary">
                {{ notification.analytics.successRate }}%
              </div>
              <div class="text-sm text-gray-600">Success Rate</div>
            </div>
          </div>

          <!-- Success Rate Progress Bar -->
          <div class="mt-6">
            <div class="flex justify-between text-sm text-gray-600 mb-2">
              <span>Success Rate</span>
              <span>{{ notification.analytics.successRate }}%</span>
            </div>
            <div class="w-full bg-gray-200 rounded-full h-3">
              <div
                class="h-3 rounded-full transition-all duration-300"
                :class="
                  notification.analytics.successRate >= 95
                    ? 'bg-green-500'
                    : notification.analytics.successRate >= 80
                    ? 'bg-yellow-500'
                    : 'bg-red-500'
                "
                :style="{ width: notification.analytics.successRate + '%' }"
              ></div>
            </div>
          </div>

          <!-- Additional Metrics -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
            <div class="text-center p-4 border rounded-lg">
              <div class="text-2xl font-bold text-blue-600">
                {{ notification.analytics.openRate }}%
              </div>
              <div class="text-sm text-gray-600">Open Rate</div>
            </div>
            <div class="text-center p-4 border rounded-lg">
              <div class="text-2xl font-bold text-purple-600">
                {{ notification.analytics.clickRate }}%
              </div>
              <div class="text-sm text-gray-600">Click Rate</div>
            </div>
          </div>
        </template>
      </rs-card>

      <!-- Scheduling Information -->
      <rs-card>
        <template #header>
          <h2 class="text-xl font-semibold">Scheduling Information</h2>
        </template>
        <template #body>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Created At</label
              >
              <p class="text-base text-gray-900 dark:text-gray-100">
                {{ formatDateTime(notification.createdAt) }}
                <span class="text-sm text-gray-500"
                  >({{ formatTimeAgo(notification.createdAt) }})</span
                >
              </p>
            </div>
            <div v-if="notification.scheduledAt">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Scheduled At</label
              >
              <p class="text-base text-gray-900 dark:text-gray-100">
                {{ formatDateTime(notification.scheduledAt) }}
              </p>
            </div>
            <div v-if="notification.sentAt">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >Sent At</label
              >
              <p class="text-base text-gray-900 dark:text-gray-100">
                {{ formatDateTime(notification.sentAt) }}
              </p>
            </div>
          </div>
        </template>
      </rs-card>

      <!-- Content Information -->
      <rs-card v-if="notification.contentType === 'template' && notification.template">
        <template #header>
          <h2 class="text-xl font-semibold">Template Information</h2>
        </template>
        <template #body>
          <div class="space-y-4">
            <div>
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >
                Template Name
              </label>
              <p class="text-base text-gray-900 dark:text-gray-100">
                {{ notification.template.name }}
              </p>
            </div>
            <div v-if="notification.template.subject">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >
                Email Subject
              </label>
              <p class="text-base text-gray-900 dark:text-gray-100">
                {{ notification.template.subject }}
              </p>
            </div>
            <div v-if="notification.template.pushTitle">
              <label
                class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >
                Push Title
              </label>
              <p class="text-base text-gray-900 dark:text-gray-100">
                {{ notification.template.pushTitle }}
              </p>
            </div>
          </div>
        </template>
      </rs-card>

      <!-- Custom Content -->
      <template v-else>
        <rs-card v-if="notification.emailSubject || notification.emailContent">
          <template #header>
            <h2 class="text-xl font-semibold">Email Content</h2>
          </template>
          <template #body>
            <div class="space-y-4">
              <div v-if="notification.emailSubject">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >
                  Subject
                </label>
                <p class="text-base text-gray-900 dark:text-gray-100">
                  {{ notification.emailSubject }}
                </p>
              </div>
              <div v-if="notification.emailContent">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >
                  Content
                </label>
                <div
                  class="prose dark:prose-invert max-w-none"
                  v-html="notification.emailContent"
                ></div>
              </div>
              <div v-if="notification.callToActionText && notification.callToActionUrl">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >
                  Call to Action
                </label>
                <div class="flex items-center gap-2">
                  <rs-button as="a" :href="notification.callToActionUrl" target="_blank">
                    {{ notification.callToActionText }}
                  </rs-button>
                </div>
              </div>
            </div>
          </template>
        </rs-card>

        <rs-card v-if="notification.pushTitle || notification.pushBody">
          <template #header>
            <h2 class="text-xl font-semibold">Push Notification Content</h2>
          </template>
          <template #body>
            <div class="space-y-4">
              <div v-if="notification.pushTitle">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >
                  Title
                </label>
                <p class="text-base text-gray-900 dark:text-gray-100">
                  {{ notification.pushTitle }}
                </p>
              </div>
              <div v-if="notification.pushBody">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >
                  Body
                </label>
                <p class="text-base text-gray-900 dark:text-gray-100">
                  {{ notification.pushBody }}
                </p>
              </div>
              <div v-if="notification.pushImageUrl">
                <label
                  class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
                >
                  Image
                </label>
                <img
                  :src="notification.pushImageUrl"
                  alt="Push notification image"
                  class="max-w-sm rounded-lg"
                />
              </div>
            </div>
          </template>
        </rs-card>
      </template>
    </div>
  </div>
</template>

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

definePageMeta({
  title: "Notification Details",
  middleware: ["auth"],
  requiresAuth: true,
});

// Get route params
const route = useRoute();
const router = useRouter();
const notificationId = route.params.id;

// Reactive data
const isLoading = ref(true);
const notification = ref(null);

// Get notifications composable
const { getNotificationById } = useNotifications();

// Helper functions
const getChannelIcon = (channel) => {
  const icons = {
    email: "material-symbols:mail-outline-rounded",
    push: "material-symbols:notifications-active-outline-rounded",
    sms: "material-symbols:sms-outline-rounded",
    "in-app": "material-symbols:chat-bubble-outline-rounded",
  };
  return icons[channel] || "material-symbols:help-outline-rounded";
};

const getPriorityVariant = (priority) => {
  const variants = {
    critical: "danger",
    high: "warning",
    medium: "info",
    low: "secondary",
  };
  return variants[priority] || "secondary";
};

const getStatusVariant = (status) => {
  const variants = {
    draft: "secondary",
    scheduled: "info",
    sending: "warning",
    sent: "success",
    failed: "danger",
    cancelled: "secondary",
  };
  return variants[status] || "secondary";
};

const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

const formatDateTime = (dateString) => {
  return new Date(dateString).toLocaleDateString("en-US", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const formatTimeAgo = (dateString) => {
  const now = new Date();
  const date = new Date(dateString);
  const diffInHours = Math.floor((now - date) / (1000 * 60 * 60));

  if (diffInHours < 1) return "Just now";
  if (diffInHours < 24) return `${diffInHours}h ago`;
  if (diffInHours < 48) return "Yesterday";

  const diffInDays = Math.floor(diffInHours / 24);
  return `${diffInDays}d ago`;
};

// Methods
const editNotification = () => {
  router.push(`/notification/edit/${notificationId}`);
};

const loadNotification = async () => {
  isLoading.value = true;

  console.log("Notification ID:", notificationId);

  try {
    const data = await getNotificationById(notificationId);
    notification.value = data;
  } catch (error) {
    console.error("Error loading notification:", error);
    notification.value = null;
  } finally {
    isLoading.value = false;
  }
};

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