<script lang="ts" setup>
import { Link } from '@inertiajs/vue3'
import AccountLayout from '@/Layouts/AccountLayout.vue'
import { resolveSubscriptionStatusColor, formatPrice } from '@/utils/resolvers'
import type { Subscription } from '@/types'

interface Props {
  subscriptions: Subscription[]
}

defineOptions({ layout: AccountLayout })

defineProps<Props>()
</script>

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div class="text-h4 font-weight-bold">Subscriptions</div>
      <Link href="/plans" class="text-decoration-none">
        <VBtn>Browse Plans</VBtn>
      </Link>
    </div>

    <VCard v-if="subscriptions.length === 0">
      <VCardText class="text-center py-12">
        <div class="text-medium-emphasis mb-4">You don't have any subscriptions yet.</div>
        <Link href="/plans" class="text-primary text-body-2 font-weight-medium text-decoration-none">Browse Available Plans</Link>
      </VCardText>
    </VCard>

    <div v-else class="d-flex flex-column ga-4">
      <VCard
        v-for="subscription in subscriptions"
        :key="subscription.id"
      >
        <VCardText>
          <div class="d-flex align-center justify-space-between">
            <div>
              <div class="text-h6 font-weight-bold">
                {{ subscription.plan_name || subscription.type }}
              </div>
              <div class="text-body-2 text-medium-emphasis mt-1">
                {{ subscription.gateway || 'stripe' }} &middot;
                <span v-if="subscription.current_period_end">
                  Renews {{ new Date(subscription.current_period_end).toLocaleDateString() }}
                </span>
              </div>
            </div>
            <div class="d-flex align-center ga-3">
              <VChip
                :color="resolveSubscriptionStatusColor(subscription.stripe_status)"
                size="small"
                class="text-capitalize"
              >
                {{ subscription.stripe_status }}
              </VChip>
              <Link
                :href="`/subscriptions/${subscription.id}`"
                class="text-primary text-body-2 font-weight-medium text-decoration-none"
              >
                Manage
              </Link>
            </div>
          </div>

          <div v-if="subscription.plan_price" class="text-body-2 text-medium-emphasis mt-3">
            {{ formatPrice(subscription.plan_price, subscription.plan_billing_cycle) }}
          </div>

          <div v-if="subscription.ends_at" class="text-body-2 text-error mt-2">
            Cancels on {{ new Date(subscription.ends_at).toLocaleDateString() }}
          </div>
        </VCardText>
      </VCard>
    </div>
  </div>
</template>
