<script setup lang="ts">
import { refDebounced } from '@vueuse/core'

const page = ref(1)
const search = ref('')
const customerTypeFilter = ref<string | null>(null)
const debouncedSearch = refDebounced(search, 300)

const customerTypeItems = [
  { label: 'All Types',   value: null         },
  { label: 'Individual',  value: 'individual' },
  { label: 'Corporate',   value: 'corporate'  }
]

watch([debouncedSearch, customerTypeFilter], () => { page.value = 1 })

const { data, pending, refresh } = useCustomer('/customers', {
  query: computed(() => {
    const filters: Record<string, string> = {}
    let i = 0

    if (debouncedSearch.value) {
      filters[`filters[${i}][field]`] = 'search'
      filters[`filters[${i}][op]`]    = '=='
      filters[`filters[${i}][value]`] = debouncedSearch.value
      i++
    }

    if (customerTypeFilter.value) {
      filters[`filters[${i}][field]`] = 'customer_type'
      filters[`filters[${i}][op]`]    = '=='
      filters[`filters[${i}][value]`] = customerTypeFilter.value
      i++
    }

    return {
    page_size: 20,
    page: page.value,
      ...filters
    }
  })
})

const customers = computed(() => data.value?.data ?? [])
const meta      = computed(() => data.value?.meta)

// display helpers
const customerName = (c: any) =>
  c.customer_type === 'corporate'
    ? (c.commercial_name || c.legal_name)
    : `${c.first_name} ${c.last_name}`

const customerSubtitle = (c: any) =>
  c.customer_type === 'corporate' ? c.ruc : c.email

const customerTypeColor = (type: string) =>
  type === 'corporate' ? 'purple' : 'blue'
</script>

<template>
  <div class="p-8 space-y-8 bg-gray-50 min-h-screen">
    <!-- Header -->
    <div class="flex justify-between items-center">
      <div>
        <h1 class="text-3xl text-slate-900 font-bold">Customers</h1>
        <p class="text-gray-500 text-sm">Customer Relationship Management</p>
      </div>
      <div class="flex items-center gap-3">
        <UBadge color="gray" variant="soft" size="lg">
          {{ meta?.total_count ?? 0 }} customers
        </UBadge>
        <NuxtLink to="/customers/new">
        <UButton icon="i-heroicons-plus" color="primary">New Customer</UButton>
        </NuxtLink>
      </div>
    </div>

    <!-- Search + Filters -->
    <div class="flex gap-4 items-center flex-wrap">
      <UInput
        v-model="search"
        icon="i-heroicons-magnifying-glass"
        placeholder="Search by name, email, RUC..."
        class="w-80"
      />
      <USelect
        v-model="customerTypeFilter"
        :items="customerTypeItems"
        class="w-44"
      />
      <UButton
        icon="i-heroicons-arrow-path"
        color="gray"
        variant="soft"
        :loading="pending"
        @click="refresh()"
      >
        Refresh
      </UButton>
    </div>

    <!-- Loading -->
    <div v-if="pending" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
      <UCard v-for="n in 6" :key="n">
        <div class="h-32 animate-pulse bg-gray-200 rounded" />
      </UCard>
    </div>

    <template v-else>
      <div class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        <NuxtLink v-for="c in customers" :key="c.id" :to="`/customers/${c.id}`">
          <UCard class="hover:shadow-md transition-shadow cursor-pointer h-full">
            <div class="space-y-3">
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-3 min-w-0">
                  <UAvatar :alt="customerName(c)" size="md" />
                  <div class="min-w-0">
                    <p class="font-semibold text-slate-900 truncate">{{ customerName(c) }}</p>
                    <p class="text-sm text-gray-400 truncate">{{ customerSubtitle(c) }}</p>
                  </div>
                </div>
                <UBadge :color="customerTypeColor(c.customer_type)" variant="soft" size="xs" class="flex-shrink-0">
                  {{ c.customer_type === 'corporate' ? 'Corporate' : 'Individual' }}
                </UBadge>
              </div>

              <!-- Individual fields -->
              <div v-if="c.customer_type !== 'corporate'" class="space-y-1 text-sm pt-2 border-t">
                <div class="flex justify-between">
                  <span class="text-gray-500">Phone</span>
                  <span>{{ c.phone ?? '—' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-500">Birth Date</span>
                  <span>{{ c.birth_date ?? '—' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-500">Gender</span>
                  <span class="capitalize">{{ c.gender ?? '—' }}</span>
                </div>
              </div>

              <!-- Corporate fields -->
              <div v-else class="space-y-1 text-sm pt-2 border-t">
                <div class="flex justify-between">
                  <span class="text-gray-500">Legal Name</span>
                  <span class="truncate max-w-40 text-right">{{ c.legal_name ?? '—' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-500">RUC</span>
                  <span class="font-mono">{{ c.ruc ?? '—' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-500">Legal Rep</span>
                  <span>{{ c.legal_rep_name ?? '—' }}</span>
                </div>
              </div>
            </div>
          </UCard>
        </NuxtLink>

        <div v-if="customers.length === 0" class="col-span-3 text-center py-16 text-gray-400">
          <UIcon name="i-heroicons-users" class="w-12 h-12 mx-auto mb-4" />
          <p class="text-lg font-medium">No customers found</p>
          <p class="text-sm">Try adjusting your search or create a new customer</p>
        </div>
      </div>

      <div v-if="meta && meta.total_pages > 1" class="flex justify-center">
        <UPagination
          v-model="page"
          :total="meta.total_count"
          :page-count="meta.page_size"
        />
      </div>
    </template>
  </div>
</template>
