<template>
  <v-card class="span-12 panel-pad">
    <div class="toolbar-row mb-3">
      <div>
        <h2 class="section-title">Section 179 limits</h2>
        <p class="quiet text-body-2">
          Annual §179 deduction limits and investment-phaseout thresholds. The engine caps each asset’s §179 deduction at the
          applicable year’s limit (less any dollar-for-dollar phaseout). Enterprise/empowerment-zone assets get the increased limit
          configured on their depreciation zone.
        </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="tax_year"
      :page-size="10"
      has-actions
      empty-text="No §179 limits configured — deductions are uncapped."
    >
      <template #cell-base_limit="{ row }">${{ Number(row.base_limit).toLocaleString() }}</template>
      <template #cell-phaseout_threshold="{ row }">${{ Number(row.phaseout_threshold).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="480">
      <v-card>
        <v-card-title>{{ form.exists ? `Edit ${form.tax_year}` : 'New §179 limit 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.base_limit" type="number" label="Base deduction limit ($)" prefix="$" />
            <v-text-field v-model.number="form.phaseout_threshold" type="number" label="Investment phaseout threshold ($)" prefix="$" />
          </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-dialog v-model="deleteDialog" max-width="440">
      <v-card>
        <v-card-title class="text-error">Delete limit</v-card-title>
        <v-card-text>
          <p>Remove the §179 limit for <strong>{{ deleteTarget?.tax_year }}</strong>? Assets placed in service that year fall back to
            the nearest earlier configured 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';

function blankForm() {
  return { exists: false, tax_year: new Date().getFullYear(), base_limit: 0, phaseout_threshold: 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: 'tax_year', label: 'Tax year' },
        { key: 'base_limit', label: 'Base deduction limit' },
        { key: 'phaseout_threshold', label: 'Phaseout threshold' }
      ]
    };
  },
  mounted() {
    this.load();
  },
  methods: {
    async api(path, options = {}) {
      return apiRequest(path, this.token, options);
    },
    async load() {
      this.error = '';
      try {
        const data = await (await this.api('/api/section-179-limits')).json();
        this.limits = data.limits;
      } 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, base_limit: row.base_limit, phaseout_threshold: row.phaseout_threshold };
      this.dialogError = '';
      this.dialog = true;
    },
    async save() {
      if (!this.form.tax_year) return;
      this.saving = true;
      this.dialogError = '';
      try {
        const method = this.form.exists ? 'PUT' : 'POST';
        const url = this.form.exists ? `/api/section-179-limits/${this.form.tax_year}` : '/api/section-179-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-179-limits/${target.tax_year}`, { method: 'DELETE' });
        await this.load();
        this.$emit('updated');
      } catch (error) {
        this.error = error.message;
      }
    }
  }
};
</script>
