<template>
  <v-card class="span-12 panel-pad">
    <div class="toolbar-row mb-3">
      <div>
        <h2 class="section-title">§280F passenger-auto limits</h2>
        <p class="quiet text-body-2">
          Annual luxury-automobile depreciation caps (IRS Rev. Proc., indexed yearly). When an asset is flagged as a
          <strong>passenger automobile</strong>, the engine limits each year's depreciation to the applicable cap (reduced by
          business-use %), using the higher first-year figure when bonus depreciation is claimed.
        </p>
      </div>
      <v-spacer />
      <v-btn color="primary" prepend-icon="mdi-plus" @click="openNew">New year</v-btn>
    </div>

    <DataTable :columns="columns" :rows="limits" row-key="pis_year" :page-size="10" has-actions empty-text="No §280F caps configured — passenger autos are uncapped.">
      <template #cell-year1_no_bonus="{ row }">${{ Number(row.year1_no_bonus).toLocaleString() }}</template>
      <template #cell-year1_bonus="{ row }">${{ Number(row.year1_bonus).toLocaleString() }}</template>
      <template #cell-year2="{ row }">${{ Number(row.year2).toLocaleString() }}</template>
      <template #cell-year3="{ row }">${{ Number(row.year3).toLocaleString() }}</template>
      <template #cell-year4plus="{ row }">${{ Number(row.year4plus).toLocaleString() }}</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="confirmDelete(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="520">
      <v-card>
        <v-card-title>{{ form.exists ? `Edit ${form.pis_year}` : 'New §280F year' }}</v-card-title>
        <v-card-text>
          <div class="form-grid">
            <v-text-field v-model.number="form.pis_year" type="number" label="Placed-in-service year *" :disabled="form.exists" />
            <v-text-field v-model.number="form.year1_no_bonus" type="number" prefix="$" label="Year 1 (no bonus)" />
            <v-text-field v-model.number="form.year1_bonus" type="number" prefix="$" label="Year 1 (with bonus)" />
            <v-text-field v-model.number="form.year2" type="number" prefix="$" label="Year 2" />
            <v-text-field v-model.number="form.year3" type="number" prefix="$" label="Year 3" />
            <v-text-field v-model.number="form.year4plus" type="number" prefix="$" label="Year 4 and later" />
          </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.pis_year" @click="save">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="deleteDialog" max-width="440">
      <v-card>
        <v-card-title class="text-error">Delete caps</v-card-title>
        <v-card-text><p>Remove the §280F caps for <strong>{{ deleteTarget?.pis_year }}</strong>? Autos placed in service that year fall back to the nearest earlier year (or become uncapped).</p></v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="deleteDialog = false">Cancel</v-btn>
          <v-btn color="error" prepend-icon="mdi-delete-outline" @click="performDelete">Delete</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-card>
</template>

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

// §280F passenger-automobile annual depreciation caps editor (Admin → Application Configuration). Mirrors
// the §179 limits editor; CRUD against /api/section-280f-limits.
function blankForm() {
  return { exists: false, pis_year: new Date().getFullYear(), year1_no_bonus: 0, year1_bonus: 0, year2: 0, year3: 0, year4plus: 0 };
}

export default {
  components: { DataTable },
  props: { token: { type: String, required: true } },
  emits: ['updated'],
  data() {
    return {
      limits: [], dialog: false, deleteDialog: false, deleteTarget: null, form: blankForm(), saving: false, error: '', dialogError: '',
      columns: [
        { key: 'pis_year', label: 'Year' },
        { key: 'year1_no_bonus', label: 'Y1 (no bonus)' },
        { key: 'year1_bonus', label: 'Y1 (bonus)' },
        { key: 'year2', label: 'Y2' },
        { key: 'year3', label: 'Y3' },
        { key: 'year4plus', label: 'Y4+' }
      ]
    };
  },
  mounted() { this.load(); },
  methods: {
    async api(path, options = {}) { return apiRequest(path, this.token, options); },
    async load() {
      this.error = '';
      try { this.limits = (await (await this.api('/api/section-280f-limits')).json()).limits; }
      catch (error) { this.error = error.message; }
    },
    openNew() { this.form = blankForm(); this.dialogError = ''; this.dialog = true; },
    openEdit(row) { this.form = { exists: true, ...row }; this.dialogError = ''; this.dialog = true; },
    async save() {
      if (!this.form.pis_year) return;
      this.saving = true; this.dialogError = '';
      try {
        const method = this.form.exists ? 'PUT' : 'POST';
        const url = this.form.exists ? `/api/section-280f-limits/${this.form.pis_year}` : '/api/section-280f-limits';
        await this.api(url, { method, body: JSON.stringify(this.form) });
        this.dialog = false;
        await this.load();
        this.$emit('updated');
      } catch (error) { this.dialogError = error.message; } finally { this.saving = false; }
    },
    confirmDelete(row) { this.deleteTarget = row; this.deleteDialog = true; },
    async performDelete() {
      const target = this.deleteTarget;
      this.deleteDialog = false; this.deleteTarget = null;
      if (!target) return;
      try { await this.api(`/api/section-280f-limits/${target.pis_year}`, { method: 'DELETE' }); await this.load(); this.$emit('updated'); }
      catch (error) { this.error = error.message; }
    }
  }
};
</script>
