<script lang="ts" setup>
import { Link } from '@inertiajs/vue3'
import { computed } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'

interface EmailTemplate {
  id: number
  slug: string
  name: string
  subject: string
  body: string
  available_variables: string[]
  is_active: boolean
  updated_at: string
}

interface Props {
  templates: EmailTemplate[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const tableHeaders = computed(() => [
  { title: 'Name', key: 'name', sortable: true },
  { title: 'Subject', key: 'subject', sortable: true },
  { title: 'Status', key: 'is_active', sortable: true, align: 'center' as const },
  { title: 'Last Modified', key: 'updated_at', sortable: true },
  { title: 'Actions', key: 'actions', sortable: false, align: 'center' as const },
])

interface CategoryGroup {
  name: string
  icon: string
  color: string
  slugs: string[]
}

const categories: CategoryGroup[] = [
  { name: 'Payment', icon: 'tabler-credit-card', color: 'success', slugs: ['payment-succeeded', 'payment-failed'] },
  { name: 'Subscription', icon: 'tabler-repeat', color: 'primary', slugs: ['subscription-created', 'subscription-cancelled'] },
  { name: 'Service', icon: 'tabler-server', color: 'info', slugs: ['service-provisioned', 'service-credentials'] },
  { name: 'Invoice', icon: 'tabler-file-invoice', color: 'warning', slugs: ['invoice-generated'] },
]

function getCategoryForTemplate(slug: string): CategoryGroup | undefined {
  return categories.find(cat => cat.slugs.includes(slug))
}

const groupedTemplates = computed(() => {
  return categories.map(category => ({
    ...category,
    templates: props.templates.filter(t => category.slugs.includes(t.slug)),
  })).filter(group => group.templates.length > 0)
})

function formatDate(dateString: string): string {
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Email Templates
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Customize notification email content sent to customers
        </div>
      </div>
    </div>

    <!-- Template Groups -->
    <div
      v-for="group in groupedTemplates"
      :key="group.name"
      class="mb-6"
    >
      <div class="d-flex align-center gap-2 mb-3">
        <VAvatar
          :color="group.color"
          variant="tonal"
          size="32"
          rounded
        >
          <VIcon
            :icon="group.icon"
            size="18"
          />
        </VAvatar>
        <span class="text-h6 font-weight-medium">{{ group.name }}</span>
      </div>

      <VCard>
        <VDataTable
          :headers="tableHeaders"
          :items="group.templates"
          :items-per-page="-1"
          hover
          class="text-no-wrap"
          :hide-default-footer="true"
        >
          <!-- Name -->
          <template #item.name="{ item }">
            <div class="d-flex align-center gap-2">
              <span class="font-weight-medium">{{ item.name }}</span>
              <VChip
                size="x-small"
                variant="tonal"
                color="secondary"
                class="font-monospace"
              >
                {{ item.slug }}
              </VChip>
            </div>
          </template>

          <!-- Subject -->
          <template #item.subject="{ item }">
            <span class="text-body-2 text-truncate d-inline-block" style="max-width: 350px;">
              {{ item.subject }}
            </span>
          </template>

          <!-- Status -->
          <template #item.is_active="{ item }">
            <VChip
              :color="item.is_active ? 'success' : 'error'"
              size="small"
            >
              {{ item.is_active ? 'Active' : 'Inactive' }}
            </VChip>
          </template>

          <!-- Last Modified -->
          <template #item.updated_at="{ item }">
            <span class="text-body-2">{{ formatDate(item.updated_at) }}</span>
          </template>

          <!-- Actions -->
          <template #item.actions="{ item }">
            <Link
              :href="`/email-templates/${item.id}/edit`"
              class="text-decoration-none"
            >
              <VBtn
                icon="tabler-edit"
                variant="text"
                size="small"
                color="primary"
              />
            </Link>
          </template>

          <!-- No data -->
          <template #no-data>
            <div class="text-center py-8">
              <VIcon
                icon="tabler-mail-cog"
                size="48"
                color="disabled"
                class="mb-2"
              />
              <div class="text-medium-emphasis">
                No email templates found.
              </div>
            </div>
          </template>
        </VDataTable>
      </VCard>
    </div>

    <!-- Empty state when no templates at all -->
    <VCard v-if="templates.length === 0">
      <VCardText class="text-center py-12">
        <VIcon
          icon="tabler-mail-cog"
          size="64"
          color="disabled"
          class="mb-4"
        />
        <div class="text-h6 text-medium-emphasis mb-2">
          No Email Templates
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Run the EmailTemplateSeeder to create default templates.
        </div>
      </VCardText>
    </VCard>
  </div>
</template>
