<template>
  <v-card class="span-12 panel-pad">
    <h2 class="section-title mb-1">Email &amp; alerts (SMTP)</h2>
    <p class="quiet text-body-2 mb-3">Mail server used for reminder and alert emails. Leave the password blank to keep the stored value.</p>
    <div class="form-grid">
      <v-switch v-model="form.alerts_enabled" label="Enable email alerts" color="primary" density="compact" hide-details />
      <v-text-field v-model.number="form.alerts_lead_days" type="number" label="Lead days (warn ahead of due date)" />
      <v-text-field v-model="form.alerts_recipients" class="full" label="Alert recipients (comma-separated)" />
      <v-text-field v-model="form.smtp_host" label="SMTP host" />
      <v-text-field v-model.number="form.smtp_port" type="number" label="SMTP port" />
      <v-switch v-model="form.smtp_secure" label="Use TLS (secure)" color="primary" density="compact" hide-details />
      <v-text-field v-model="form.smtp_user" label="SMTP username" />
      <v-text-field
        v-model="form.smtp_password"
        type="password"
        :label="settings.smtp_password_set ? 'SMTP password (unchanged)' : 'SMTP password'"
        autocomplete="new-password"
      />
      <v-text-field v-model="form.smtp_from" class="full" label="From address" />
    </div>
    <div class="toolbar-row mt-3">
      <v-text-field v-model="testTo" label="Send test to (optional)" density="compact" hide-details style="max-width: 280px" />
      <v-btn variant="tonal" prepend-icon="mdi-email-fast-outline" :loading="testing" @click="sendTest">Send test</v-btn>
      <v-spacer />
      <v-btn color="primary" prepend-icon="mdi-content-save" :loading="saving" @click="save">Save settings</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';

export default {
  props: {
    token: { type: String, required: true }
  },
  data() {
    return {
      settings: {},
      form: {
        alerts_enabled: false,
        alerts_lead_days: 30,
        alerts_recipients: '',
        smtp_host: '',
        smtp_port: 587,
        smtp_secure: false,
        smtp_user: '',
        smtp_password: '',
        smtp_from: ''
      },
      testTo: '',
      saving: false,
      testing: false,
      status: '',
      statusType: 'success'
    };
  },
  mounted() {
    this.load();
  },
  methods: {
    async api(path, options = {}) {
      return apiRequest(path, this.token, options);
    },
    async load() {
      const data = await (await this.api('/api/notifications/settings')).json();
      this.settings = data.settings;
      this.form = {
        alerts_enabled: data.settings.alerts_enabled,
        alerts_lead_days: data.settings.alerts_lead_days,
        alerts_recipients: data.settings.alerts_recipients,
        smtp_host: data.settings.smtp_host,
        smtp_port: data.settings.smtp_port,
        smtp_secure: data.settings.smtp_secure,
        smtp_user: data.settings.smtp_user,
        smtp_password: '',
        smtp_from: data.settings.smtp_from
      };
    },
    async save() {
      this.saving = true;
      this.status = '';
      try {
        const payload = { ...this.form };
        if (!payload.smtp_password) delete payload.smtp_password;
        const data = await (await this.api('/api/notifications/settings', { method: 'PUT', body: JSON.stringify(payload) })).json();
        this.settings = data.settings;
        this.form.smtp_password = '';
        this.statusType = 'success';
        this.status = 'Settings saved.';
      } catch (error) {
        this.statusType = 'error';
        this.status = error.message;
      } finally {
        this.saving = false;
      }
    },
    async sendTest() {
      this.testing = true;
      this.status = '';
      try {
        await this.api('/api/notifications/test', { method: 'POST', body: JSON.stringify({ to: this.testTo || undefined }) });
        this.statusType = 'success';
        this.status = `Test email sent${this.testTo ? ` to ${this.testTo}` : ''}.`;
      } catch (error) {
        this.statusType = 'error';
        this.status = `Test failed: ${error.message}`;
      } finally {
        this.testing = false;
      }
    }
  }
};
</script>
