<script lang="ts" setup>
import { Link } from '@inertiajs/vue3'
import { computed } from 'vue'
import AccountLayout from '@/Layouts/AccountLayout.vue'
import StatCard from '@/Components/StatCard.vue'
import { resolveSubscriptionStatusColor, resolveInvoiceStatusColor, resolveTicketStatusColor, resolveTicketPriorityColor, formatPrice } from '@/utils/resolvers'
import type { Subscription, Invoice, SupportTicket } from '@/types'

interface Props {
  activeServicesCount: number
  activeSubscriptionsCount: number
  activeSubscriptions: Subscription[]
  latestInvoices: Invoice[]
  pendingInvoicesAmount: string
  nextRenewalDate: string | null
  openTicketsCount: number
  recentTickets: SupportTicket[]
}

defineOptions({ layout: AccountLayout })

const props = defineProps<Props>()

function formatDate(dateString: string): string {
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

function formatCurrency(amount: string | number): string {
  return `$${parseFloat(String(amount)).toFixed(2)}`
}

const formattedNextRenewal = computed<string>(() => {
  if (!props.nextRenewalDate) {
    return 'N/A'
  }
  return formatDate(props.nextRenewalDate)
})

function formatRelativeTime(dateString: string): string {
  const date = new Date(dateString)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMinutes = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)

  if (diffMinutes < 1) {
    return 'Just now'
  }
  if (diffMinutes < 60) {
    return `${diffMinutes}m ago`
  }
  if (diffHours < 24) {
    return `${diffHours}h ago`
  }
  if (diffDays < 7) {
    return `${diffDays}d ago`
  }
  return formatDate(dateString)
}

function formatStatus(status: string): string {
  return status.replace(/_/g, ' ')
}

const unpaidInvoices = computed<Invoice[]>(() => {
  return props.latestInvoices.filter(
    (invoice: Invoice) => invoice.status === 'pending' || invoice.status === 'overdue',
  )
})
</script>

<template>
  <div>
    <div class="text-h4 font-weight-bold mb-6">
      Dashboard
    </div>

    <!-- Row 1: Stats Cards -->
    <VRow class="mb-2">
      <VCol
        cols="12"
        sm="6"
        md="3"
      >
        <StatCard
          title="Active Services"
          :stats="activeServicesCount"
          icon="tabler-server"
          color="primary"
        />
      </VCol>

      <VCol
        cols="12"
        sm="6"
        md="3"
      >
        <StatCard
          title="Subscriptions"
          :stats="activeSubscriptionsCount"
          icon="tabler-receipt"
          color="success"
        />
      </VCol>

      <VCol
        cols="12"
        sm="6"
        md="3"
      >
        <StatCard
          title="Pending Invoices"
          :stats="formatCurrency(pendingInvoicesAmount)"
          icon="tabler-file-invoice"
          color="warning"
        />
      </VCol>

      <VCol
        cols="12"
        sm="6"
        md="3"
      >
        <StatCard
          title="Next Renewal"
          :stats="formattedNextRenewal"
          icon="tabler-calendar-event"
          color="info"
        />
      </VCol>
    </VRow>

    <!-- Row 2: Active Subscriptions + Recent Invoices -->
    <VRow class="mb-2">
      <!-- Active Subscriptions -->
      <VCol
        cols="12"
        md="6"
      >
        <VCard>
          <VCardTitle class="d-flex align-center justify-space-between">
            <span>Active Subscriptions</span>
            <Link
              href="/subscriptions"
              class="text-primary text-body-2 text-decoration-none"
            >
              View All
            </Link>
          </VCardTitle>

          <VCardText v-if="activeSubscriptions.length === 0">
            <div class="text-center py-8">
              <VIcon
                icon="tabler-receipt-off"
                size="48"
                class="text-disabled mb-3"
              />
              <div class="text-body-2 text-medium-emphasis mb-3">
                No active subscriptions
              </div>
              <Link
                href="/plans"
                class="text-decoration-none"
              >
                <VBtn
                  size="small"
                  color="primary"
                >
                  Browse Plans
                </VBtn>
              </Link>
            </div>
          </VCardText>

          <VList
            v-else
            lines="three"
          >
            <template
              v-for="(subscription, index) in activeSubscriptions"
              :key="subscription.id"
            >
              <VListItem>
                <template #prepend>
                  <VAvatar
                    color="primary"
                    variant="tonal"
                    rounded
                  >
                    <VIcon icon="tabler-package" />
                  </VAvatar>
                </template>

                <VListItemTitle class="font-weight-semibold">
                  {{ subscription.plan_name || subscription.type }}
                </VListItemTitle>

                <VListItemSubtitle>
                  <div class="d-flex align-center ga-2 mt-1">
                    <VChip
                      :color="resolveSubscriptionStatusColor(subscription.stripe_status)"
                      size="x-small"
                      class="text-capitalize"
                    >
                      {{ subscription.stripe_status }}
                    </VChip>
                    <span
                      v-if="subscription.plan_price"
                      class="text-body-2"
                    >
                      {{ formatPrice(subscription.plan_price, subscription.plan_billing_cycle) }}
                    </span>
                  </div>
                  <div
                    v-if="subscription.current_period_end"
                    class="text-body-2 mt-1"
                  >
                    Next billing: {{ formatDate(subscription.current_period_end) }}
                  </div>
                  <div
                    v-if="subscription.ends_at"
                    class="text-error text-body-2 mt-1"
                  >
                    Cancels on {{ formatDate(subscription.ends_at) }}
                  </div>
                </VListItemSubtitle>

                <template #append>
                  <Link
                    :href="`/subscriptions/${subscription.id}`"
                    class="text-decoration-none"
                  >
                    <VBtn
                      variant="text"
                      size="small"
                      color="primary"
                    >
                      Manage
                    </VBtn>
                  </Link>
                </template>
              </VListItem>

              <VDivider
                v-if="index < activeSubscriptions.length - 1"
                inset
              />
            </template>
          </VList>
        </VCard>
      </VCol>

      <!-- Recent Invoices -->
      <VCol
        cols="12"
        md="6"
      >
        <VCard>
          <VCardTitle class="d-flex align-center justify-space-between">
            <span>Recent Invoices</span>
            <Link
              href="/billing/invoices"
              class="text-primary text-body-2 text-decoration-none"
            >
              View All
            </Link>
          </VCardTitle>

          <VCardText v-if="latestInvoices.length === 0">
            <div class="text-center py-8">
              <VIcon
                icon="tabler-file-off"
                size="48"
                class="text-disabled mb-3"
              />
              <div class="text-body-2 text-medium-emphasis">
                No invoices yet
              </div>
            </div>
          </VCardText>

          <VTable
            v-else
            density="comfortable"
          >
            <thead>
              <tr>
                <th>Invoice #</th>
                <th>Date</th>
                <th>Status</th>
                <th class="text-end">
                  Amount
                </th>
                <th class="text-end" />
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="invoice in latestInvoices"
                :key="invoice.id"
              >
                <td class="text-body-2">
                  {{ invoice.number }}
                </td>
                <td class="text-body-2">
                  {{ formatDate(invoice.created_at) }}
                </td>
                <td>
                  <VChip
                    :color="resolveInvoiceStatusColor(invoice.status)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ invoice.status }}
                  </VChip>
                </td>
                <td class="text-end text-body-2">
                  {{ formatCurrency(invoice.total) }}
                </td>
                <td class="text-end">
                  <Link
                    v-if="invoice.status === 'pending' || invoice.status === 'overdue'"
                    :href="`/checkout/${invoice.id}`"
                    class="text-decoration-none"
                  >
                    <VBtn
                      variant="text"
                      size="small"
                      color="primary"
                    >
                      Pay
                    </VBtn>
                  </Link>
                  <a
                    v-else-if="invoice.status === 'paid'"
                    :href="`/billing/invoices/${invoice.id}/download`"
                    class="text-primary text-decoration-none text-body-2"
                  >
                    Download
                  </a>
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>
    </VRow>

    <!-- Row 3: Recent Support Tickets -->
    <VRow class="mb-2">
      <VCol cols="12">
        <VCard>
          <VCardTitle class="d-flex align-center justify-space-between">
            <span>Recent Support Tickets</span>
            <Link
              href="/tickets"
              class="text-primary text-body-2 text-decoration-none"
            >
              View All
            </Link>
          </VCardTitle>

          <VCardText v-if="recentTickets.length === 0">
            <div class="text-center py-8">
              <VIcon
                icon="tabler-ticket-off"
                size="48"
                class="text-disabled mb-3"
              />
              <div class="text-body-2 text-medium-emphasis mb-3">
                No support tickets yet
              </div>
              <Link
                href="/tickets/create"
                class="text-decoration-none"
              >
                <VBtn
                  size="small"
                  color="primary"
                >
                  Create Ticket
                </VBtn>
              </Link>
            </div>
          </VCardText>

          <VTable
            v-else
            density="comfortable"
          >
            <thead>
              <tr>
                <th>Subject</th>
                <th>Status</th>
                <th>Priority</th>
                <th>Last Updated</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="ticket in recentTickets"
                :key="ticket.id"
              >
                <td>
                  <Link
                    :href="`/tickets/${ticket.id}`"
                    class="text-primary text-decoration-none font-weight-medium"
                  >
                    {{ ticket.subject }}
                  </Link>
                </td>
                <td>
                  <VChip
                    :color="resolveTicketStatusColor(ticket.status)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ formatStatus(ticket.status) }}
                  </VChip>
                </td>
                <td>
                  <VChip
                    :color="resolveTicketPriorityColor(ticket.priority)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ ticket.priority }}
                  </VChip>
                </td>
                <td class="text-body-2">
                  {{ formatRelativeTime(ticket.updated_at) }}
                </td>
              </tr>
            </tbody>
          </VTable>
        </VCard>
      </VCol>
    </VRow>

    <!-- Row 4: Quick Actions -->
    <VRow>
      <VCol cols="12">
        <VCard>
          <VCardTitle>Quick Actions</VCardTitle>
          <VCardText>
            <div class="d-flex flex-wrap ga-3">
              <Link
                href="/plans"
                class="text-decoration-none"
              >
                <VBtn
                  color="primary"
                  variant="tonal"
                >
                  <VIcon
                    icon="tabler-search"
                    start
                  />
                  Browse Plans
                </VBtn>
              </Link>

              <Link
                href="/billing/invoices"
                class="text-decoration-none"
              >
                <VBtn
                  color="info"
                  variant="tonal"
                >
                  <VIcon
                    icon="tabler-file-invoice"
                    start
                  />
                  View All Invoices
                </VBtn>
              </Link>

              <Link
                href="/billing"
                class="text-decoration-none"
              >
                <VBtn
                  color="success"
                  variant="tonal"
                >
                  <VIcon
                    icon="tabler-credit-card"
                    start
                  />
                  Manage Payment Methods
                </VBtn>
              </Link>

              <Link
                href="/tickets/create"
                class="text-decoration-none"
              >
                <VBtn
                  color="warning"
                  variant="tonal"
                >
                  <VIcon
                    icon="tabler-headset"
                    start
                  />
                  Open Support Ticket
                  <VBadge
                    v-if="openTicketsCount > 0"
                    :content="openTicketsCount"
                    color="error"
                    inline
                    class="ms-1"
                  />
                </VBtn>
              </Link>
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>
  </div>
</template>
