<template>
  <q-page padding>
    <div class="row items-center q-mb-md">
      <q-btn flat dense icon="arrow_back" to="/rapports" class="q-mr-sm" />
      <div class="text-h6 text-weight-bold">Âge des comptes à recevoir</div>
      <q-space />
      <q-btn flat dense icon="download" label="CSV" @click="downloadCSV" :disable="!rows.length" />
    </div>

    <!-- Filters -->
    <div class="row q-col-gutter-sm q-mb-md items-end">
      <div class="col-auto">
        <q-input v-model="asOfDate" type="date" label="En date du" dense outlined style="width:160px" />
      </div>
      <div class="col-auto">
        <q-btn color="primary" label="Générer" icon="play_arrow" @click="loadReport" :loading="loading" />
      </div>
    </div>

    <!-- Summary buckets -->
    <div v-if="summary" class="row q-col-gutter-sm q-mb-md">
      <div v-for="b in bucketCards" :key="b.key" class="col-auto">
        <div class="ops-card text-center" style="min-width:120px">
          <div class="text-caption text-grey-6">{{ b.label }}</div>
          <div class="text-h6 text-weight-bold" :class="b.color">{{ formatMoney(summary[b.key]) }}</div>
        </div>
      </div>
    </div>

    <!-- Chart -->
    <div v-if="summary" class="ops-card q-mb-md" style="height:280px;position:relative">
      <canvas ref="chartCanvas"></canvas>
    </div>

    <!-- Data table -->
    <q-table
      v-if="rows.length"
      :rows="rows"
      :columns="columns"
      row-key="customer"
      flat bordered
      class="ops-table"
      :pagination="{ rowsPerPage: 50, sortBy: 'total', descending: true }"
      dense
      :filter="search"
    >
      <template #top-right>
        <q-input v-model="search" dense outlined placeholder="Filtrer..." clearable style="width:200px">
          <template #prepend><q-icon name="search" /></template>
        </q-input>
      </template>

      <template #body-cell-total="props">
        <q-td :props="props">
          <span class="text-weight-bold text-negative">{{ formatMoney(props.value) }}</span>
        </q-td>
      </template>

      <template #body-cell-d120="props">
        <q-td :props="props">
          <span :class="props.value > 0 ? 'text-negative text-weight-bold' : ''">
            {{ props.value > 0 ? formatMoney(props.value) : '—' }}
          </span>
        </q-td>
      </template>
    </q-table>

    <!-- Empty state -->
    <div v-if="!loading && !rows.length" class="text-center text-grey-5 q-pa-xl">
      <q-icon name="account_balance_wallet" size="64px" class="q-mb-md" />
      <div>Sélectionnez une date et cliquez <b>Générer</b></div>
    </div>
  </q-page>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { fetchARReport } from 'src/api/reports'
import { formatMoney } from 'src/composables/useFormatters'
import Chart from 'chart.js/auto'

const asOfDate = ref(new Date().toISOString().slice(0, 10))
const loading = ref(false)
const rows = ref([])
const summary = ref(null)
const search = ref('')
const chartCanvas = ref(null)
let chartInstance = null

const bucketCards = [
  { key: 'current', label: 'Courant', color: 'text-positive' },
  { key: 'd30', label: '30 jours', color: 'text-warning' },
  { key: 'd60', label: '60 jours', color: 'text-orange' },
  { key: 'd90', label: '90 jours', color: 'text-deep-orange' },
  { key: 'd120', label: '120+ jours', color: 'text-negative' },
  { key: 'total', label: 'Total dû', color: 'text-negative' },
]

const columns = [
  { name: 'customer', label: '#Client', field: 'customer', align: 'left', sortable: true },
  { name: 'customer_name', label: 'Nom', field: 'customer_name', align: 'left', sortable: true },
  { name: 'current', label: 'Courant', field: 'current', align: 'right', sortable: true, format: v => v > 0 ? formatMoney(v) : '—' },
  { name: 'd30', label: '30 jours', field: 'd30', align: 'right', sortable: true, format: v => v > 0 ? formatMoney(v) : '—' },
  { name: 'd60', label: '60 jours', field: 'd60', align: 'right', sortable: true, format: v => v > 0 ? formatMoney(v) : '—' },
  { name: 'd90', label: '90 jours', field: 'd90', align: 'right', sortable: true, format: v => v > 0 ? formatMoney(v) : '—' },
  { name: 'd120', label: '120+', field: 'd120', align: 'right', sortable: true },
  { name: 'total', label: 'Total', field: 'total', align: 'right', sortable: true },
]

async function loadReport () {
  loading.value = true
  try {
    const res = await fetchARReport(asOfDate.value)
    rows.value = res.rows || []
    summary.value = res.summary || null
    await nextTick()
    renderChart()
  } catch (e) {
    console.error('AR report error:', e)
  } finally {
    loading.value = false
  }
}

function renderChart () {
  if (chartInstance) chartInstance.destroy()
  if (!chartCanvas.value || !summary.value) return

  const s = summary.value
  chartInstance = new Chart(chartCanvas.value, {
    type: 'doughnut',
    data: {
      labels: ['Courant', '30 jours', '60 jours', '90 jours', '120+ jours'],
      datasets: [{
        data: [s.current, s.d30, s.d60, s.d90, s.d120],
        backgroundColor: ['#10b981', '#f59e0b', '#f97316', '#ef4444', '#991b1b'],
        borderWidth: 2,
        borderColor: '#fff',
      }],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: { position: 'right', labels: { font: { size: 12 } } },
        tooltip: { callbacks: { label: ctx => ctx.label + ': ' + formatMoney(ctx.parsed) } },
      },
    },
  })
}

function downloadCSV () {
  if (!rows.value.length) return
  const header = ['#Client', 'Nom', 'Courant', '30 jours', '60 jours', '90 jours', '120+ jours', 'Total']
  const csvRows = rows.value.map(r => [
    r.customer, `"${r.customer_name}"`,
    r.current.toFixed(2), r.d30.toFixed(2), r.d60.toFixed(2),
    r.d90.toFixed(2), r.d120.toFixed(2), r.total.toFixed(2),
  ])
  if (summary.value) {
    const s = summary.value
    csvRows.push(['', 'TOTAL', s.current.toFixed(2), s.d30.toFixed(2), s.d60.toFixed(2), s.d90.toFixed(2), s.d120.toFixed(2), s.total.toFixed(2)])
  }
  const csv = [header, ...csvRows].map(r => r.join(',')).join('\n')
  const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8' })
  const a = document.createElement('a')
  a.href = URL.createObjectURL(blob)
  a.download = `age_comptes_${asOfDate.value}.csv`
  a.click()
}
</script>
