<script lang="ts" setup>
import { Link, router } from '@inertiajs/vue3'
import { ref, watch } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { formatPrice } from '@/utils/resolvers'
import type { PaginatedResponse, StatusColor } from '@/types'

interface OrderUser {
  id: number
  name: string
  email: string
}

interface OrderPlan {
  id: number
  name: string
  service_type: string
  price: string
  billing_cycle: string
}

interface OrderItem {
  id: number
  user_id: number
  plan_id: number
  order_number: string
  status: string
  total: string
  currency: string
  payment_gateway: string | null
  created_at: string
  user: OrderUser | null
  plan: OrderPlan | null
}

interface Filters {
  search: string
  status: string
}

interface Props {
  orders: PaginatedResponse<OrderItem>
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const search = ref<string>(props.filters.search)
const status = ref<string>(props.filters.status)

const statusOptions = [
  { title: 'All Statuses', value: '' },
  { title: 'Pending', value: 'pending' },
  { title: 'Processing', value: 'processing' },
  { title: 'Completed', value: 'completed' },
  { title: 'Cancelled', value: 'cancelled' },
  { title: 'Failed', value: 'failed' },
]

let searchTimeout: ReturnType<typeof setTimeout> | null = null

function applyFilters(): void {
  router.get('/orders', {
    search: search.value || undefined,
    status: status.value || undefined,
  }, {
    preserveState: true,
    preserveScroll: true,
  })
}

watch(search, () => {
  if (searchTimeout) clearTimeout(searchTimeout)
  searchTimeout = setTimeout(applyFilters, 300)
})

watch(status, () => {
  applyFilters()
})

function resolveOrderStatusColor(statusVal: string): StatusColor {
  const map: Record<string, StatusColor> = {
    pending: 'warning',
    processing: 'info',
    completed: 'success',
    cancelled: 'error',
    failed: 'error',
  }
  return map[statusVal] ?? 'secondary'
}

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

<template>
  <div>
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Orders
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage all customer orders
        </div>
      </div>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="8">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search by order number, customer name, or email..."
              density="compact"
              clearable
              hide-details
              @click:clear="search = ''"
            />
          </VCol>
          <VCol cols="12" md="4">
            <VSelect
              v-model="status"
              :items="statusOptions"
              density="compact"
              hide-details
              label="Status"
            />
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Orders Table -->
    <VCard>
      <VCardText v-if="orders.data.length === 0" class="text-center py-12">
        <VIcon icon="tabler-shopping-cart-off" size="48" color="disabled" class="mb-2" />
        <div class="text-medium-emphasis">
          No orders found.
        </div>
      </VCardText>

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>Order #</th>
            <th>Customer</th>
            <th>Plan</th>
            <th class="text-end">
              Total
            </th>
            <th>Status</th>
            <th>Gateway</th>
            <th>Created</th>
            <th class="text-center">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="order in orders.data" :key="order.id">
            <td class="text-body-2 font-weight-medium">
              {{ order.order_number }}
            </td>
            <td>
              <div class="d-flex flex-column">
                <span class="text-body-2 font-weight-medium">{{ order.user?.name ?? 'Unknown' }}</span>
                <span class="text-caption text-medium-emphasis">{{ order.user?.email ?? '' }}</span>
              </div>
            </td>
            <td class="text-body-2">
              {{ order.plan?.name ?? 'N/A' }}
            </td>
            <td class="text-end text-body-2 font-weight-medium">
              {{ formatPrice(order.total) }}
            </td>
            <td>
              <VChip
                :color="resolveOrderStatusColor(order.status)"
                size="small"
                class="text-capitalize"
              >
                {{ order.status }}
              </VChip>
            </td>
            <td class="text-body-2 text-capitalize">
              {{ order.payment_gateway ?? '---' }}
            </td>
            <td class="text-body-2">
              {{ formatDate(order.created_at) }}
            </td>
            <td class="text-center">
              <Link :href="`/orders/${order.id}`">
                <VBtn variant="text" size="small" color="primary">
                  <VIcon icon="tabler-eye" size="18" />
                </VBtn>
              </Link>
            </td>
          </tr>
        </tbody>
      </VTable>

      <!-- Pagination -->
      <VCardText v-if="orders.last_page > 1" class="d-flex align-center justify-center pt-2">
        <VPagination
          :model-value="orders.data.length > 0 ? Math.ceil((orders.from ?? 1) / 25) : 1"
          :length="orders.last_page"
          :total-visible="7"
          @update:model-value="(page: number) => router.get('/orders', { ...props.filters, page }, { preserveState: true, preserveScroll: true })"
        />
      </VCardText>

      <VCardText v-if="orders.total > 0" class="text-center text-caption text-medium-emphasis">
        Showing {{ orders.from }} to {{ orders.to }} of {{ orders.total }} orders
      </VCardText>
    </VCard>
  </div>
</template>
