<template>
  <q-page padding>
    <!-- Search + filters -->
    <div class="row items-center q-mb-md q-col-gutter-sm">
      <div class="col-12 col-md-4">
        <q-input
          v-model="search" dense outlined placeholder="Nom, ID legacy, numéro de compte..."
          class="ops-search" @update:model-value="onSearchInput" @keyup.enter="doSearch" autofocus
        >
          <template #prepend><q-icon name="search" /></template>
          <template #append>
            <q-spinner v-if="loading" size="16px" color="grey-5" />
            <q-icon v-else-if="search" name="close" class="cursor-pointer" @click="search = ''; clients = []; total = 0" />
          </template>
        </q-input>
      </div>
      <div class="col-auto">
        <q-btn-toggle v-model="statusFilter" no-caps dense unelevated
          toggle-color="indigo-6" color="grey-3" text-color="grey-8"
          :options="[
            { label: 'Tous', value: 'all' },
            { label: 'Actifs', value: 'active' },
            { label: 'Inactifs', value: 'disabled' },
          ]"
          @update:model-value="doSearch"
        />
      </div>
      <q-space />
      <div class="text-caption text-grey-6">{{ total.toLocaleString() }} clients</div>
    </div>

    <!-- Client table -->
    <q-table
      :rows="clients" :columns="columns" row-key="name"
      flat bordered class="ops-table"
      :loading="loading"
      :pagination="pagination"
      @request="onRequest"
      @row-click="(_, row) => $router.push('/clients/' + row.name)"
      style="cursor:pointer"
    >
      <template #body-cell-status="props">
        <q-td :props="props">
          <span class="ops-badge" :class="props.row.disabled ? 'inactive' : 'active'">
            {{ props.row.disabled ? 'Inactif' : 'Actif' }}
          </span>
        </q-td>
      </template>
      <template #body-cell-customer_name="props">
        <q-td :props="props">
          <div class="text-weight-medium" @dblclick.stop>
            <InlineField :value="props.row.customer_name" field="customer_name" doctype="Customer" :docname="props.row.name"
              placeholder="Nom" @saved="v => props.row.customer_name = v.value" />
          </div>
          <div class="text-caption text-grey-6">
            {{ props.row.name }}
            <template v-if="props.row.legacy_customer_id"> &middot; {{ props.row.legacy_customer_id }}</template>
          </div>
        </q-td>
      </template>
      <template #body-cell-customer_type="props">
        <q-td :props="props" @dblclick.stop>
          <InlineField :value="props.row.customer_type" field="customer_type" doctype="Customer" :docname="props.row.name"
            type="select" :options="['Individual', 'Company']"
            @saved="v => props.row.customer_type = v.value" />
        </q-td>
      </template>
      <template #body-cell-customer_group="props">
        <q-td :props="props" @dblclick.stop>
          <InlineField :value="props.row.customer_group" field="customer_group" doctype="Customer" :docname="props.row.name"
            type="select" :options="customerGroups"
            @saved="v => props.row.customer_group = v.value" />
        </q-td>
      </template>
    </q-table>
  </q-page>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { listDocs, countDocs } from 'src/api/erp'
import InlineField from 'src/components/shared/InlineField.vue'

const route = useRoute()
const customerGroups = ['Commercial', 'Individual', 'Government', 'Non Profit']
const search = ref(route.query.q || '')
const statusFilter = ref('active')
const clients = ref([])
const loading = ref(false)
const total = ref(0)
const pagination = ref({ page: 1, rowsPerPage: 25, rowsNumber: 0 })
let searchTimer = null

const columns = [
  { name: 'customer_name', label: 'Client', field: 'customer_name', align: 'left', sortable: true },
  { name: 'legacy_customer_id', label: 'ID Legacy', field: 'legacy_customer_id', align: 'left' },
  { name: 'customer_type', label: 'Type', field: 'customer_type', align: 'left' },
  { name: 'customer_group', label: 'Groupe', field: 'customer_group', align: 'left' },
  { name: 'territory', label: 'Territoire', field: 'territory', align: 'left' },
  { name: 'status', label: 'Statut', align: 'center' },
]

function onSearchInput () {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    pagination.value.page = 1
    doSearch()
  }, 300)
}

async function doSearch () {
  loading.value = true
  const filters = {}
  let or_filters

  if (statusFilter.value === 'active') filters.disabled = 0
  else if (statusFilter.value === 'disabled') filters.disabled = 1

  if (search.value.trim()) {
    const q = '%' + search.value.trim() + '%'
    or_filters = [
      ['customer_name', 'like', q],
      ['name', 'like', q],
      ['legacy_customer_id', 'like', q],
    ]
  }

  const [data, count] = await Promise.all([
    listDocs('Customer', {
      filters,
      or_filters,
      fields: ['name', 'customer_name', 'customer_type', 'customer_group', 'territory', 'disabled', 'legacy_customer_id'],
      limit: pagination.value.rowsPerPage,
      offset: (pagination.value.page - 1) * pagination.value.rowsPerPage,
      orderBy: 'customer_name asc',
    }),
    countDocs('Customer', filters, or_filters),
  ])

  clients.value = data
  total.value = count
  pagination.value.rowsNumber = count
  loading.value = false
}

function onRequest (props) {
  pagination.value.page = props.pagination.page
  pagination.value.rowsPerPage = props.pagination.rowsPerPage
  doSearch()
}

onMounted(() => doSearch())
watch(() => route.query.q, (q) => { if (q) { search.value = q; doSearch() } })
</script>
