<template>
  <v-card class="span-12 panel-pad">
    <div class="toolbar-row mb-3">
      <div>
        <h2 class="section-title">Short tax years</h2>
        <p class="quiet text-body-2">
          Define a tax year shorter than 12 months for the <strong>active company</strong>. That year's MACRS depreciation is
          prorated by months ÷ 12 (simplified method — most accurate for a placed-in-service short year).
        </p>
      </div>
      <v-spacer />
      <v-btn color="primary" prepend-icon="mdi-plus" @click="openNew">New year</v-btn>
    </div>

    <DataTable :columns="columns" :rows="years" row-key="tax_year" :page-size="10" has-actions empty-text="No short tax years — all years are full 12-month years.">
      <template #cell-months="{ row }">{{ row.months }} months ({{ Math.round((row.months / 12) * 100) }}%)</template>
      <template #actions="{ row }">
        <v-btn icon="mdi-pencil" size="small" variant="text" @click="openEdit(row)" />
        <v-btn icon="mdi-delete-outline" size="small" variant="text" color="error" @click="remove(row)" />
      </template>
    </DataTable>
    <v-alert v-if="error" type="error" density="compact" class="mt-3">{{ error }}</v-alert>

    <v-dialog v-model="dialog" max-width="460">
      <v-card>
        <v-card-title>{{ form.exists ? `Edit ${form.tax_year}` : 'New short tax year' }}</v-card-title>
        <v-card-text>
          <div class="form-grid">
            <v-text-field v-model.number="form.tax_year" type="number" label="Tax year *" :disabled="form.exists" />
            <v-text-field v-model.number="form.months" type="number" label="Months in the tax year (1–12)" min="1" max="12" />
            <v-text-field v-model="form.note" class="full" label="Note (optional)" />
          </div>
          <v-alert v-if="dialogError" type="error" density="compact" class="mt-2">{{ dialogError }}</v-alert>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="dialog = false">Cancel</v-btn>
          <v-btn color="primary" prepend-icon="mdi-content-save" :loading="saving" :disabled="!form.tax_year" @click="save">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-card>
</template>

<script>
import DataTable from './DataTable.vue';
import { apiRequest } from '../services/api';

// Short-tax-year config (Admin → Application Configuration), company-scoped via the active company. CRUD
// against /api/short-tax-years; the engine prorates that year's MACRS depreciation by months ÷ 12.
function blankForm() {
  return { exists: false, tax_year: new Date().getFullYear(), months: 12, note: '' };
}

export default {
  components: { DataTable },
  props: { token: { type: String, required: true } },
  emits: ['updated'],
  data() {
    return {
      years: [], dialog: false, form: blankForm(), saving: false, error: '', dialogError: '',
      columns: [{ key: 'tax_year', label: 'Tax year' }, { key: 'months', label: 'Length' }, { key: 'note', label: 'Note' }]
    };
  },
  mounted() { this.load(); },
  methods: {
    async api(path, options = {}) { return apiRequest(path, this.token, options); },
    async load() {
      this.error = '';
      try { this.years = (await (await this.api('/api/short-tax-years')).json()).years; }
      catch (error) { this.error = error.message; }
    },
    openNew() { this.form = blankForm(); this.dialogError = ''; this.dialog = true; },
    openEdit(row) { this.form = { exists: true, tax_year: row.tax_year, months: row.months, note: row.note || '' }; this.dialogError = ''; this.dialog = true; },
    async save() {
      if (!this.form.tax_year) return;
      this.saving = true; this.dialogError = '';
      try {
        await this.api('/api/short-tax-years', { method: 'POST', body: JSON.stringify(this.form) });
        this.dialog = false;
        await this.load();
        this.$emit('updated');
      } catch (error) { this.dialogError = error.message; } finally { this.saving = false; }
    },
    async remove(row) {
      if (!window.confirm(`Remove the short tax year ${row.tax_year}?`)) return;
      try { await this.api(`/api/short-tax-years/${row.tax_year}`, { method: 'DELETE' }); await this.load(); this.$emit('updated'); }
      catch (error) { this.error = error.message; }
    }
  }
};
</script>
