<template>
  <NuxtLayout
    :page-title="t('admin.stripe-plans')"
    :parent="{
      label: t('admin.title'),
      to: localePath('/dashboard/admin')
    }"
    type="admin"
  >
    <UPageBody>
      <PageRefresh :on-refresh="refreshPlans" />
      <PageMainCard
        :title="t('admin.stripePlans.title')"
        :description="t('admin.stripePlans.description')"
        :icon="useSolarIcon('bag')"
        :loading="loading"
        :on-refresh="refreshPlans"
        :show-refresh-button="false"
      >
        <template #header-actions>
          <UButton
            icon="i-lucide-refresh-cw"
            :loading="loading"
            color="primary"
            :ui="{ leadingIcon: 'size-4' }"
            @click="syncStripeData"
          >
            {{ t('admin.stripePlans.syncButton') }}
          </UButton>
        </template>
        <SuperAdminPlanCard
          v-for="product in uniqueProducts"
          :key="product.id"
          :title="product.name"
        >
          <template #actions>
            <UButton
              icon="i-lucide-trash-2"
              color="error"
              variant="soft"
              size="sm"
              :loading="deletingProduct === product.id"
              @click="deleteProduct(product.id)"
            />
          </template>
          <div class="divide-y divide-neutral-100 dark:divide-white/10">
            <div
              v-for="plan in getProductPlans(product.id)"
              :key="plan.id"
              class="flex items-center gap-4 py-4"
            >
              <div
                class="flex h-10 w-10 items-center justify-center rounded-lg bg-neutral-100 dark:bg-white/10"
              >
                <UIcon
                  name="i-lucide-package"
                  class="h-5 w-5"
                />
              </div>
              <div class="flex-1">
                <p class="text-sm font-medium capitalize">
                  {{ plan.interval }}
                </p>
                <p class="text-xs text-neutral-500 dark:text-white/50">
                  {{ plan.id }}
                </p>
              </div>
              <div class="text-right">
                <p class="font-bold">
                  {{ formatPrice(plan.unitAmount) }}
                </p>
                <p class="text-xs text-neutral-500 dark:text-white/50">
                  {{ t('admin.stripePlans.per', { interval: plan.interval }) }}
                </p>
              </div>
            </div>
          </div>

          <div class="mt-4">
            <p class="text-sm text-neutral-500 dark:text-white/50">
              {{ product.description }}
            </p>

            <!-- Product features -->
            <div
              v-if="product.features && product.features.length"
              class="mt-2"
            >
              <ul class="text-sm text-neutral-600 dark:text-white/70">
                <li
                  v-for="feature in product.features"
                  :key="feature.name"
                  class="flex items-center gap-1.5"
                >
                  <UIcon
                    name="i-lucide-check"
                    class="h-4 w-4 text-emerald-500"
                  />
                  {{ feature.name }}
                </li>
              </ul>
            </div>
          </div>
        </SuperAdminPlanCard>
      </PageMainCard>
    </UPageBody>
  </NuxtLayout>
</template>

<script lang="ts" setup>
import type { Price, Product } from '~/types/database'

type PlanWithProduct = Price & { product: Product }
const loading = ref(false)
const toast = useToast()
const log = useLogger('Stripe Plans')
const { data: plans, refresh: refreshPlans }
  = await useApiFetch<PlanWithProduct[]>('/api/stripe/plans')

const plansList = computed<PlanWithProduct[]>(() => {
  const plansData = plans.value
  return Array.isArray(plansData) ? plansData : []
})

// Compute unique products from plans
const uniqueProducts = computed(() => {
  if (!plansList.value.length) return []

  const productMap = new Map()
  plansList.value.forEach((plan: PlanWithProduct) => {
    if (plan.product && !productMap.has(plan.product.id)) {
      productMap.set(plan.product.id, plan.product)
    }
  })

  return Array.from(productMap.values())
})

// Get all plans for a specific product
const getProductPlans = (productId: string) => {
  if (!plansList.value.length) return []
  return plansList.value.filter((plan: PlanWithProduct) => plan.productId === productId)
}

const formatPrice = (price: number) => {
  if (!price) return '$0'
  return new Intl.NumberFormat('nl-BE', {
    style: 'currency',
    currency: 'EUR',
    minimumFractionDigits: 0
  }).format(price / 100)
}

const syncStripeData = async () => {
  try {
    loading.value = true
    const apiCall = useApiCall()
    await apiCall('/api/super-admin/stripe/sync-products')
    await refreshPlans()
    toast.add({
      title: t('admin.stripePlans.messages.syncSuccess'),
      icon: 'i-lucide-check-circle',
      color: 'success'
    })
  } catch (error) {
    toast.add({
      title: t('admin.stripePlans.messages.syncError'),
      description:
        error instanceof Error ? error.message : t('admin.stripePlans.messages.unexpectedError'),
      icon: 'i-lucide-alert-circle',
      color: 'error'
    })
  } finally {
    loading.value = false
  }
}
const deletingProduct = ref<string | null>(null)
const deleteProduct = async (productId: string) => {
  try {
    deletingProduct.value = productId
    const apiCall = useApiCall()
    await apiCall(`/api/super-admin/stripe/${productId}`, {
      method: 'DELETE'
    })
    await refreshPlans()
    toast.add({
      title: t('admin.stripePlans.messages.deleteSuccess'),
      icon: 'i-lucide-check-circle',
      color: 'success'
    })
  } catch (error) {
    log.error('Failed to delete product:', error)
    toast.add({
      title: t('admin.stripePlans.messages.deleteError'),
      description:
        error instanceof Error ? error.message : t('admin.stripePlans.messages.unexpectedError'),
      icon: 'i-lucide-alert-circle',
      color: 'error'
    })
  } finally {
    deletingProduct.value = null
  }
}
const { t } = useI18n()
const localePath = useLocalePath()

definePageMeta({
  layout: 'dashboard',
  middleware: ['super-admin'],
  colorMode: 'light'
})
</script>
