<template>
  <div>
    <div class="page-header">
      <NuxtLink :to="`/admin/communes/${slug}`" style="color: var(--color-text-muted);">&larr; {{ slug }}</NuxtLink>
      <h1>Parametres tarifs</h1>
    </div>

    <div v-if="saved" class="alert alert-success">Parametres enregistres.</div>
    <div v-if="published" class="alert alert-success">Courbe publiee avec succes (p0 = {{ publishedP0.toFixed(3) }} €/m3).</div>
    <div v-if="error" class="alert alert-error">{{ error }}</div>

    <div class="card" style="max-width: 600px; margin-bottom: 1.5rem;">
      <form @submit.prevent="save">
        <div class="form-group">
          <label>Recettes cibles (€)</label>
          <input v-model.number="form.recettes" type="number" class="form-input" step="1000" min="0" />
        </div>
        <div class="form-group">
          <label>Abonnement (€)</label>
          <input v-model.number="form.abop" type="number" class="form-input" step="1" min="0" />
        </div>
        <div class="form-group" style="margin-bottom: 1rem;">
          <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
            <input type="checkbox" v-model="form.differentiated_tariff" />
            Tarif differencie RS / RP / PRO
          </label>
          <p style="font-size: 0.8rem; color: var(--color-text-muted); margin-top: 0.25rem;">
            Si coche, un abonnement different est applique aux residences secondaires (RS).
          </p>
        </div>
        <div v-if="form.differentiated_tariff" class="form-group">
          <label>Abonnement RS (€)</label>
          <input v-model.number="form.abos" type="number" class="form-input" step="1" min="0" />
        </div>
        <div class="grid grid-2">
          <div class="form-group">
            <label>Prix max/m3 (€)</label>
            <input v-model.number="form.pmax" type="number" class="form-input" step="0.5" min="0" />
          </div>
          <div class="form-group">
            <label>Volume max (m3)</label>
            <input v-model.number="form.vmax" type="number" class="form-input" step="100" min="0" />
          </div>
        </div>
        <button type="submit" class="btn btn-primary" :disabled="loading">
          Enregistrer
        </button>
      </form>
    </div>

    <!-- ══════════════════════════════════════════════
         COURBE DE REFERENCE — Editeur + Publier
         ══════════════════════════════════════════════ -->
    <div class="card" style="margin-bottom: 1.5rem;">
      <h3 style="margin-bottom: 0.5rem;">Courbe de reference</h3>
      <p style="font-size: 0.85rem; color: var(--color-text-muted); margin-bottom: 1rem;">
        Ajustez les parametres de la courbe Bezier, puis publiez-la. C'est la courbe initiale que les citoyens voient.
      </p>

      <!-- Curve params sliders -->
      <div class="curve-params">
        <div class="slider-group">
          <label>v<sub>inf</sub> <span class="slider-val">{{ curve.vinf.toFixed(0) }} m3</span></label>
          <input type="range" v-model.number="curve.vinf" :min="50" :max="form.vmax - 100" step="10" class="slider" />
        </div>
        <div class="slider-group">
          <label>a <span class="slider-val">{{ curve.a.toFixed(2) }}</span></label>
          <input type="range" v-model.number="curve.a" min="0" max="1" step="0.01" class="slider" />
        </div>
        <div class="slider-group">
          <label>b <span class="slider-val">{{ curve.b.toFixed(2) }}</span></label>
          <input type="range" v-model.number="curve.b" min="0" max="1" step="0.01" class="slider" />
        </div>
        <div class="slider-group">
          <label>c <span class="slider-val">{{ curve.c.toFixed(2) }}</span></label>
          <input type="range" v-model.number="curve.c" min="0" max="1" step="0.01" class="slider" />
        </div>
        <div class="slider-group">
          <label>d <span class="slider-val">{{ curve.d.toFixed(2) }}</span></label>
          <input type="range" v-model.number="curve.d" min="0" max="1" step="0.01" class="slider" />
        </div>
        <div class="slider-group">
          <label>e <span class="slider-val">{{ curve.e.toFixed(2) }}</span></label>
          <input type="range" v-model.number="curve.e" min="0" max="1" step="0.01" class="slider" />
        </div>
      </div>

      <p v-if="curveP0 !== null" style="margin: 0.75rem 0; font-size: 0.9rem;">
        <strong>p0 calcule :</strong> {{ curveP0.toFixed(3) }} €/m3
      </p>

      <div v-if="currentPublished" style="margin-bottom: 0.75rem; padding: 0.5rem 0.75rem; background: #eff6ff; border-radius: 6px; font-size: 0.82rem; color: #1e40af;">
        Courbe actuellement publiee : vinf={{ currentPublished.vinf?.toFixed(0) }}, p0={{ currentPublished.p0?.toFixed(3) }} €/m3
        <span style="color: #64748b;">({{ currentPublished.at }})</span>
      </div>

      <button class="btn btn-primary" @click="publishCurve" :disabled="publishing" style="background: #059669;">
        <span v-if="publishing">Publication...</span>
        <span v-else>Publier la courbe</span>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({ middleware: 'admin' })

const route = useRoute()
const api = useApi()
const slug = route.params.slug as string

const form = reactive({ recettes: 75000, abop: 100, abos: 100, pmax: 20, vmax: 2100, differentiated_tariff: false })
const curve = reactive({ vinf: 400, a: 0.5, b: 0.5, c: 0.5, d: 0.5, e: 0.5 })
const loading = ref(false)
const saved = ref(false)
const published = ref(false)
const publishing = ref(false)
const error = ref('')
const curveP0 = ref<number | null>(null)
const publishedP0 = ref(0)
const currentPublished = ref<{ vinf: number; p0: number; at: string } | null>(null)

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

watch(curve, () => {
  if (computeTimeout) clearTimeout(computeTimeout)
  computeTimeout = setTimeout(async () => {
    try {
      const result = await api.post<any>('/tariff/compute', {
        commune_slug: slug, vinf: curve.vinf,
        a: curve.a, b: curve.b, c: curve.c, d: curve.d, e: curve.e,
      })
      curveP0.value = result.p0
    } catch {}
  }, 200)
}, { deep: true })

onMounted(async () => {
  try {
    const params = await api.get<any>(`/communes/${slug}/params`)
    Object.assign(form, params)
    // Load published curve if exists
    if (params.published_vinf != null) {
      curve.vinf = params.published_vinf
      curve.a = params.published_a
      curve.b = params.published_b
      curve.c = params.published_c
      curve.d = params.published_d
      curve.e = params.published_e
      currentPublished.value = {
        vinf: params.published_vinf,
        p0: params.published_p0,
        at: new Date(params.published_at).toLocaleDateString('fr-FR'),
      }
    }
    // Trigger initial p0 compute
    const result = await api.post<any>('/tariff/compute', {
      commune_slug: slug, vinf: curve.vinf,
      a: curve.a, b: curve.b, c: curve.c, d: curve.d, e: curve.e,
    })
    curveP0.value = result.p0
  } catch {}
})

async function save() {
  loading.value = true
  saved.value = false
  error.value = ''
  try {
    await api.put(`/communes/${slug}/params`, form)
    saved.value = true
  } catch (e: any) {
    error.value = e.message
  } finally {
    loading.value = false
  }
}

async function publishCurve() {
  publishing.value = true
  published.value = false
  error.value = ''
  try {
    const result = await api.post<any>(`/communes/${slug}/params/publish`, {
      vinf: curve.vinf, a: curve.a, b: curve.b,
      c: curve.c, d: curve.d, e: curve.e,
    })
    publishedP0.value = result.published_p0
    published.value = true
    currentPublished.value = {
      vinf: result.published_vinf,
      p0: result.published_p0,
      at: new Date(result.published_at).toLocaleDateString('fr-FR'),
    }
  } catch (e: any) {
    error.value = e.message
  } finally {
    publishing.value = false
  }
}
</script>

<style scoped>
.curve-params {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.75rem 1.5rem;
  margin-bottom: 0.75rem;
}
@media (max-width: 600px) { .curve-params { grid-template-columns: 1fr; } }

.slider-group label {
  display: flex;
  justify-content: space-between;
  font-size: 0.82rem;
  font-weight: 500;
  margin-bottom: 0.2rem;
}
.slider-val {
  font-family: monospace;
  color: var(--color-primary, #2563eb);
  font-weight: 600;
}
.slider {
  width: 100%;
  accent-color: #2563eb;
}
</style>
