<template>
  <q-page padding>
    <div class="row items-center q-mb-sm">
      <q-btn flat dense round icon="arrow_back" to="/rapports" class="q-mr-sm" />
      <div class="text-h6 text-weight-bold">Services actifs sur comptes résiliés</div>
      <q-space />
      <q-btn outline color="primary" icon="refresh" label="Recalculer" no-caps :loading="loading" @click="load(true)" />
      <q-btn flat color="grey-7" icon="download" label="CSV" no-caps class="q-ml-sm" :disable="!rows.length" @click="exportCsv" />
    </div>

    <q-banner dense class="bg-blue-1 text-grey-9 q-mb-md" rounded>
      <template #avatar><q-icon name="cleaning_services" color="info" /></template>
      Comptes <b>résiliés dans F</b> (status 3/4/5) qui gardent des <b>services récurrents actifs</b> (charges <i>et</i> crédits) —
      F ne les désactive pas à la résiliation. Liste de ménage : désactiver les services au besoin. ⚠️ Les <b>employés</b> (internet fourni) sont des exceptions à conserver.
    </q-banner>

    <div v-if="loading && !rows.length" class="column items-center q-pa-xl text-grey-6">
      <q-spinner size="32px" color="primary" /><div class="q-mt-sm">Calcul en cours — comptes résiliés × services actifs…</div>
    </div>
    <div v-else-if="error" class="text-negative q-pa-md"><q-icon name="error" /> {{ error }}</div>

    <template v-else>
      <div class="row q-col-gutter-sm q-mb-md">
        <div class="col-6 col-sm-auto">
          <div style="background:var(--ops-surface);border:1px solid var(--ops-border);border-radius:10px;padding:10px 16px;min-width:140px">
            <div style="font-size:12px;color:var(--ops-text-muted)">Comptes résiliés</div>
            <div style="font-size:24px;font-weight:600;color:var(--ops-text)">{{ count }}</div>
          </div>
        </div>
        <div class="col-6 col-sm-auto">
          <div style="background:var(--ops-surface);border:1px solid var(--ops-border);border-radius:10px;padding:10px 16px;min-width:140px">
            <div style="font-size:12px;color:var(--ops-text-muted)">Services actifs</div>
            <div style="font-size:24px;font-weight:600;color:var(--ops-warning)">{{ services }}</div>
          </div>
        </div>
      </div>
      <div class="text-caption text-grey-7 q-mb-sm">
        <b>{{ count }}</b> compte{{ count > 1 ? 's' : '' }} résilié{{ count > 1 ? 's' : '' }} avec services actifs
        <span v-if="generated"> · généré {{ fmtTime(generated) }}</span>
      </div>

      <q-table :rows="rows" :columns="columns" row-key="customer" flat bordered :grid="$q.screen.lt.md"
        :pagination="{ rowsPerPage: 25, sortBy: 'active_services', descending: true }"
        :rows-per-page-options="[25, 50, 100, 0]" dense>
        <template #item="props">
          <div class="col-12 q-pa-xs">
            <q-card flat bordered class="q-pa-sm">
              <div class="row items-center no-wrap q-mb-xs">
                <router-link :to="'/clients/' + props.row.customer" class="text-primary text-weight-medium" style="text-decoration:none">{{ props.row.customer_name }}</router-link>
                <q-space />
                <q-badge color="negative" label="Résilié" />
              </div>
              <div class="text-caption text-grey-6 q-mb-xs">compte F #{{ props.row.account_id }} · {{ props.row.active_services }} service(s)</div>
              <div class="row justify-between text-caption"><span class="text-grey-7">Frais</span><span class="text-weight-medium">{{ money(props.row.charges) }}</span></div>
              <div class="row justify-between text-caption"><span class="text-grey-7">Crédits</span><span class="text-negative text-weight-medium">{{ money(props.row.credits) }}</span></div>
              <div class="row justify-between text-caption"><span class="text-grey-7">Total mensuel</span><span :class="props.row.total < 0 ? 'text-negative text-weight-bold' : 'text-weight-bold'">{{ money(props.row.total) }}</span></div>
            </q-card>
          </div>
        </template>
        <template #body-cell-customer="props">
          <q-td :props="props">
            <router-link :to="'/clients/' + props.row.customer" class="text-primary text-weight-medium" style="text-decoration:none">{{ props.row.customer_name }}</router-link>
            <q-badge color="negative" label="Résilié" class="q-ml-xs" />
            <div class="text-caption text-grey-6">{{ props.row.customer }} · compte F #{{ props.row.account_id }}</div>
          </q-td>
        </template>
        <template #body-cell-total="props">
          <q-td :props="props" class="text-weight-bold" :class="props.row.total < 0 ? 'text-negative' : 'text-grey-9'">{{ money(props.row.total) }}</q-td>
        </template>
        <template #body-cell-services="props">
          <q-td :props="props">
            <div v-for="(s, i) in props.row.services" :key="i" class="text-caption">
              <span :class="s.price < 0 ? 'text-negative' : 'text-grey-8'">{{ money(s.price) }}</span> · {{ s.plan || s.sku }}
              <span class="text-grey-5" v-if="s.legacy"> · F #{{ s.legacy }}</span>
            </div>
          </q-td>
        </template>
      </q-table>
    </template>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useQuasar } from 'quasar'
import { HUB_URL } from 'src/config/hub'
import { formatMoney as money, formatDateTimeShort as fmtTime } from 'src/composables/useFormatters'

const $q = useQuasar()
const rows = ref([]); const count = ref(0); const services = ref(0); const generated = ref(0)
const loading = ref(false); const error = ref('')
let pollTimer = null

const columns = [
  { name: 'customer', label: 'Client (résilié)', field: 'customer_name', align: 'left', sortable: true },
  { name: 'active_services', label: 'Services actifs', field: 'active_services', align: 'center', sortable: true },
  { name: 'charges', label: 'Frais', field: 'charges', align: 'right', sortable: true, format: v => money(v) },
  { name: 'credits', label: 'Crédits', field: 'credits', align: 'right', sortable: true, format: v => money(v) },
  { name: 'total', label: 'Total mensuel', field: 'total', align: 'right', sortable: true },
  { name: 'services', label: 'Détail des services actifs', field: 'services', align: 'left' },
]

// money = formatMoney, fmtTime = formatDateTimeShort (useFormatters, consolidation)

async function load (refresh) {
  loading.value = true; error.value = ''
  if (pollTimer) { clearTimeout(pollTimer); pollTimer = null }
  try {
    const r = await fetch(`${HUB_URL}/collab/terminated-active${refresh ? '?refresh=1' : ''}`)
    const d = await r.json()
    if (d.ready) { rows.value = d.rows || []; count.value = d.count || 0; services.value = d.services || 0; generated.value = d.generated || 0; loading.value = false }
    else if (d.error) { error.value = d.error; loading.value = false }
    else { pollTimer = setTimeout(() => load(false), 3000) }
  } catch (e) { error.value = e.message; loading.value = false }
}

function exportCsv () {
  const head = ['Client', 'ID', 'Compte F', 'Services actifs', 'Frais', 'Crédits', 'Total', 'Détail']
  const lines = rows.value.map(r => [
    r.customer_name, r.customer, r.account_id, r.active_services, r.charges, r.credits, r.total,
    r.services.map(s => `${s.plan || s.sku} (${s.price}${s.legacy ? ' F#' + s.legacy : ''})`).join(' | '),
  ].map(c => `"${String(c == null ? '' : c).replace(/"/g, '""')}"`).join(','))
  const csv = [head.join(','), ...lines].join('\n')
  const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8' })
  const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'comptes-resilies-services-actifs.csv'; a.click()
  $q.notify({ type: 'positive', message: `${rows.value.length} ligne(s) exportée(s)` })
}

onMounted(() => load(false))
</script>
