<template>
  <v-card class="span-12 panel-pad">
    <h2 class="section-title mb-1">Preventative maintenance defaults</h2>
    <p class="quiet text-body-2 mb-3">Default cadence applied when attaching a PM plan to an asset, and how many days ahead PM-due alerts are raised.</p>
    <div class="form-grid">
      <v-text-field v-model.number="form.pm_default_frequency_value" type="number" label="Default frequency (every)" />
      <v-select v-model="form.pm_default_frequency_unit" :items="pmFrequencyUnits" item-title="title" item-value="value" label="Default frequency unit" />
      <v-text-field v-model.number="form.pm_lead_days" type="number" label="Alert lead days" />
    </div>

    <v-divider class="my-4" />
    <h3 class="section-title text-body-1 mb-1">Dynamic scheduling</h3>
    <p class="quiet text-body-2 mb-2">
      Beyond static dates, PM due-dates can auto-adjust to real-world signals. With these on, a schedule becomes
      due at the <strong>earliest</strong> of its calendar date, a projected usage threshold, or an age-compressed date.
    </p>
    <v-switch
      v-model="form.pm_usage_tracking_enabled"
      color="primary"
      density="compact"
      hide-details
      label="Usage-based scheduling (meters: hours, kWh, gallons, cycles…)"
    />
    <v-switch
      v-model="form.pm_lifespan_curve_enabled"
      color="primary"
      density="compact"
      hide-details
      label="Lifespan wear curve (service more often as equipment ages)"
    />

    <div v-if="form.pm_lifespan_curve_enabled" class="form-grid mt-2">
      <v-text-field
        v-model.number="form.pm_lifespan_min_factor"
        type="number" step="0.05" min="0.1" max="1"
        label="End-of-life interval factor"
        hint="0.5 = half the interval at end of life"
        persistent-hint
      />
      <v-text-field
        v-model.number="form.pm_lifespan_curve_exponent"
        type="number" step="0.5" min="0.5" max="6"
        label="Curve aggressiveness (exponent)"
        hint="Higher holds the base cadence longer, then drops sharply"
        persistent-hint
      />
    </div>
    <v-alert v-if="form.pm_lifespan_curve_enabled" type="info" variant="tonal" density="compact" class="mt-2">
      {{ curvePreview }}
    </v-alert>

    <v-divider class="my-4" />
    <h3 class="section-title text-body-1 mb-1">Nightly schedule recompute</h3>
    <p class="quiet text-body-2 mb-2">
      A background job re-derives projected due-dates so usage and age-driven schedules stay current even when an asset
      isn’t serviced or read for a while. Runs once a day at the chosen hour (server time).
    </p>
    <v-switch
      v-model="form.pm_recompute_enabled"
      color="primary"
      density="compact"
      hide-details
      label="Enable nightly recompute"
    />
    <div v-if="form.pm_recompute_enabled" class="form-grid mt-2">
      <v-select
        v-model.number="form.pm_recompute_hour"
        :items="hourItems"
        item-title="title"
        item-value="value"
        label="Run at (hour, server time)"
      />
    </div>
    <div class="d-flex align-center mt-2" style="gap:12px">
      <v-btn size="small" variant="tonal" prepend-icon="mdi-refresh" :loading="recomputing" @click="runNow">Run now</v-btn>
      <span class="quiet text-body-2">Last run: {{ form.pm_last_recompute_at ? shortDate(form.pm_last_recompute_at) : 'Never' }}</span>
    </div>

    <div class="toolbar-row mt-3">
      <v-spacer />
      <v-btn color="primary" prepend-icon="mdi-content-save" :loading="saving" @click="save">Save PM defaults</v-btn>
    </div>
    <v-alert v-if="status" class="mt-3" density="compact" :type="statusType">{{ status }}</v-alert>
  </v-card>
</template>

<script>
import { apiRequest } from '../services/api';
import { pmFrequencyUnits } from '../constants';
import { shortDate } from '../utils/format';

export default {
  props: {
    token: { type: String, required: true }
  },
  data() {
    return {
      pmFrequencyUnits,
      form: {
        pm_default_frequency_value: 3,
        pm_default_frequency_unit: 'months',
        pm_lead_days: 7,
        pm_usage_tracking_enabled: false,
        pm_lifespan_curve_enabled: false,
        pm_lifespan_min_factor: 0.5,
        pm_lifespan_curve_exponent: 2,
        pm_recompute_enabled: false,
        pm_recompute_hour: 2,
        pm_last_recompute_at: null
      },
      recomputing: false,
      saving: false,
      status: '',
      statusType: 'success'
    };
  },
  computed: {
    hourItems() {
      return Array.from({ length: 24 }, (_, h) => ({
        title: `${String(h).padStart(2, '0')}:00`,
        value: h
      }));
    },
    // Plain-English example of the wear curve at the half-life point.
    curvePreview() {
      const min = Math.min(1, Math.max(0.1, Number(this.form.pm_lifespan_min_factor) || 0.5));
      const exp = Math.min(6, Math.max(0.5, Number(this.form.pm_lifespan_curve_exponent) || 2));
      const halfFactor = 1 - (1 - min) * Math.pow(0.5, exp);
      const base = 6; // months, illustrative
      const atHalf = Math.round(base * halfFactor * 10) / 10;
      const atEnd = Math.round(base * min * 10) / 10;
      return `Example: a ${base}-month interval becomes about ${atHalf} months at mid-life and ${atEnd} months at end of life.`;
    }
  },
  mounted() {
    this.load();
  },
  methods: {
    shortDate,
    async api(path, options = {}) {
      return apiRequest(path, this.token, options);
    },
    async load() {
      const data = await (await this.api('/api/pm-settings')).json();
      this.form = { ...this.form, ...data.settings };
    },
    async runNow() {
      this.recomputing = true;
      this.status = '';
      try {
        const data = await (await this.api('/api/pm-recompute', { method: 'POST', body: '{}' })).json();
        this.form = { ...this.form, ...data.settings };
        this.statusType = 'success';
        this.status = `Recompute complete — ${data.result.updated} of ${data.result.scanned} schedule(s) updated.`;
      } catch (error) {
        this.statusType = 'error';
        this.status = error.message;
      } finally {
        this.recomputing = false;
      }
    },
    async save() {
      this.saving = true;
      this.status = '';
      try {
        const data = await (await this.api('/api/pm-settings', { method: 'PUT', body: JSON.stringify(this.form) })).json();
        this.form = { ...this.form, ...data.settings };
        this.statusType = 'success';
        this.status = 'PM defaults saved.';
      } catch (error) {
        this.statusType = 'error';
        this.status = error.message;
      } finally {
        this.saving = false;
      }
    }
  }
};
</script>
