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

interface Customer {
  id: number
  name: string
  email: string
  phone: string | null
  company: string | null
  status: string
  services_count: number
  subscriptions_count: number
  created_at: string
}

interface Filters {
  search: string
  status: string
  sort: string
  direction: string
}

interface Props {
  customers: PaginatedResponse<Customer>
  filters: Filters
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

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

const statusOptions = [
  { title: 'All', value: '' },
  { title: 'Active', value: 'active' },
  { title: 'Suspended', value: 'suspended' },
  { title: 'Banned', value: 'banned' },
]

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

watch(search, (value: string) => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    applyFilters({ search: value })
  }, 400)
})

watch(statusFilter, (value: string) => {
  applyFilters({ status: value })
})

function applyFilters(overrides: Partial<Filters> = {}): void {
  router.get('/customers', {
    search: overrides.search ?? search.value,
    status: overrides.status ?? statusFilter.value,
    sort: props.filters.sort,
    direction: props.filters.direction,
  }, {
    preserveState: true,
    replace: true,
  })
}

function resolveUserStatusColor(status: string): string {
  const map: Record<string, string> = {
    active: 'success',
    suspended: 'warning',
    banned: 'error',
  }
  return map[status] ?? '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>
    <!-- Page Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div>
        <div class="text-h4 font-weight-bold">
          Customers
        </div>
        <div class="text-body-2 text-medium-emphasis">
          Manage customer accounts and view their details
        </div>
      </div>
      <VChip color="primary" variant="tonal" size="small">
        {{ customers.total }} total
      </VChip>
    </div>

    <!-- Filters -->
    <VCard class="mb-6">
      <VCardText>
        <VRow>
          <VCol cols="12" md="6">
            <VTextField
              v-model="search"
              prepend-inner-icon="tabler-search"
              placeholder="Search by name or email..."
              variant="outlined"
              density="compact"
              clearable
              hide-details
            />
          </VCol>
          <VCol cols="12" md="4">
            <div class="d-flex align-center ga-2">
              <VChip
                v-for="option in statusOptions"
                :key="option.value"
                :color="statusFilter === option.value ? 'primary' : undefined"
                :variant="statusFilter === option.value ? 'flat' : 'tonal'"
                class="cursor-pointer"
                @click="statusFilter = option.value"
              >
                {{ option.title }}
              </VChip>
            </div>
          </VCol>
        </VRow>
      </VCardText>
    </VCard>

    <!-- Customers Table -->
    <VCard>
      <VCardText v-if="customers.data.length === 0" class="text-center py-12">
        <VIcon icon="tabler-users-minus" size="48" color="disabled" class="mb-2" />
        <div class="text-medium-emphasis">
          No customers found.
        </div>
      </VCardText>

      <VTable v-else density="comfortable" hover>
        <thead>
          <tr>
            <th>Customer</th>
            <th>Status</th>
            <th class="text-center">
              Services
            </th>
            <th class="text-center">
              Subscriptions
            </th>
            <th>Created</th>
            <th class="text-end">
              Actions
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="customer in customers.data" :key="customer.id">
            <td>
              <div class="d-flex align-center gap-3 py-2">
                <VAvatar color="primary" variant="tonal" size="38">
                  <span class="text-body-2 font-weight-medium">
                    {{ customer.name.charAt(0).toUpperCase() }}
                  </span>
                </VAvatar>
                <div>
                  <div class="text-body-2 font-weight-medium">
                    {{ customer.name }}
                  </div>
                  <div class="text-caption text-medium-emphasis">
                    {{ customer.email }}
                  </div>
                </div>
              </div>
            </td>
            <td>
              <VChip
                :color="resolveUserStatusColor(customer.status)"
                size="small"
                class="text-capitalize"
              >
                {{ customer.status }}
              </VChip>
            </td>
            <td class="text-center">
              <VChip size="small" variant="tonal" color="info">
                {{ customer.services_count }}
              </VChip>
            </td>
            <td class="text-center">
              <VChip size="small" variant="tonal" color="primary">
                {{ customer.subscriptions_count }}
              </VChip>
            </td>
            <td class="text-body-2">
              {{ formatDate(customer.created_at) }}
            </td>
            <td class="text-end">
              <Link
                :href="`/customers/${customer.id}`"
                class="text-decoration-none"
              >
                <VBtn
                  variant="text"
                  color="primary"
                  size="small"
                >
                  <VIcon icon="tabler-eye" start />
                  View
                </VBtn>
              </Link>
            </td>
          </tr>
        </tbody>
      </VTable>

      <!-- Pagination -->
      <VCardText v-if="customers.last_page > 1" class="d-flex align-center justify-center pt-4">
        <VPagination
          :model-value="Math.ceil((customers.from || 1) / 15)"
          :length="customers.last_page"
          :total-visible="7"
          rounded
          @update:model-value="(page: number) => router.get('/customers', { ...props.filters, page }, { preserveState: true })"
        />
      </VCardText>
    </VCard>
  </div>
</template>
