<template>
  <v-card class="span-12 panel-pad">
    <div class="toolbar-row mb-3">
      <div>
        <h2 class="section-title">Asset classes</h2>
        <p class="quiet text-body-2">
          IRS asset classes (recovery periods) used to pre-populate a category’s class number. Seeded from the IRS tables and fully editable.
        </p>
      </div>
      <v-spacer />
      <v-select
        v-model="sourceFilter"
        :items="sourceFilterItems"
        item-title="title"
        item-value="value"
        label="Source"
        density="compact"
        hide-details
        style="max-width:190px"
      />
      <v-btn color="primary" prepend-icon="mdi-plus" @click="openNew">New asset class</v-btn>
    </div>

    <DataTable
      :columns="columns"
      :rows="filteredRows"
      row-key="id"
      :page-size="15"
      has-actions
      searchable
      search-placeholder="Filter by description or class number"
      empty-text="No asset classes."
    >
      <template #cell-class_number="{ row }">
        <span class="font-weight-bold">{{ row.class_number || '—' }}</span>
      </template>
      <template #cell-gds="{ row }">{{ row.gds ?? '—' }}</template>
      <template #cell-ads="{ row }">{{ row.ads ?? '—' }}</template>
      <template #cell-source="{ row }">
        <v-chip size="x-small" variant="tonal">{{ sourceLabel(row.source) }}</v-chip>
      </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>

    <!-- Create / edit -->
    <v-dialog v-model="dialog" max-width="560">
      <v-card>
        <v-card-title>{{ form.id ? 'Edit asset class' : 'New asset class' }}</v-card-title>
        <v-card-text>
          <v-text-field v-model="form.description" label="Description *" autofocus />
          <div class="form-grid">
            <v-text-field v-model="form.class_number" label="Class number" placeholder="00.12" />
            <v-select v-model="form.source" :items="sourceItems" item-title="title" item-value="value" label="Source" />
            <v-text-field v-model.number="form.gds" type="number" label="GDS recovery (years)" />
            <v-text-field v-model.number="form.ads" type="number" label="ADS recovery (years)" />
          </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.description.trim()" @click="save">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Delete confirmation -->
    <v-dialog v-model="deleteDialog" max-width="480">
      <v-card>
        <v-card-title class="text-error">Delete asset class</v-card-title>
        <v-card-text>
          <p class="mb-2">Delete <strong>“{{ deleteTarget?.description }}”</strong>{{ deleteTarget?.class_number ? ` (${deleteTarget.class_number})` : '' }}?</p>
          <v-alert
            :type="deleteTarget && deleteTarget.category_count ? 'warning' : 'info'"
            variant="tonal"
            density="comfortable"
          >
            <template v-if="deleteTarget && deleteTarget.category_count">
              {{ deleteTarget.category_count }} categor{{ deleteTarget.category_count === 1 ? 'y' : 'ies' }} use this class number — they keep
              their value; it just won’t appear in the lookup anymore.
            </template>
            <template v-else>This class isn’t referenced by any category.</template>
          </v-alert>
        </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';

const SOURCE_LABELS = { common: 'Common', industry: 'Manufacturing', business: 'Business', custom: 'Custom' };

function blankForm() {
  return { id: null, description: '', class_number: '', gds: null, ads: null, source: 'custom' };
}

export default {
  components: { DataTable },
  props: {
    token: { type: String, required: true }
  },
  emits: ['updated'],
  data() {
    return {
      rows: [],
      sourceFilter: 'all',
      dialog: false,
      deleteDialog: false,
      deleteTarget: null,
      form: blankForm(),
      saving: false,
      error: '',
      dialogError: '',
      sourceItems: Object.entries(SOURCE_LABELS).map(([value, title]) => ({ title, value })),
      columns: [
        { key: 'class_number', label: 'Class #' },
        { key: 'description', label: 'Description' },
        { key: 'gds', label: 'GDS', format: 'number' },
        { key: 'ads', label: 'ADS', format: 'number' },
        { key: 'source', label: 'Source', sortable: false },
        { key: 'category_count', label: 'Categories', format: 'number' }
      ]
    };
  },
  computed: {
    sourceFilterItems() {
      return [{ title: 'All sources', value: 'all' }, ...this.sourceItems];
    },
    filteredRows() {
      if (this.sourceFilter === 'all') return this.rows;
      return this.rows.filter((r) => r.source === this.sourceFilter);
    }
  },
  mounted() {
    this.load();
  },
  methods: {
    async api(path, options = {}) {
      return apiRequest(path, this.token, options);
    },
    sourceLabel(source) {
      return SOURCE_LABELS[source] || source;
    },
    async load() {
      this.error = '';
      try {
        const data = await (await this.api('/api/asset-classes')).json();
        this.rows = data.assetClasses;
      } catch (error) {
        this.error = error.message;
      }
    },
    openNew() {
      this.form = blankForm();
      this.dialogError = '';
      this.dialog = true;
    },
    openEdit(row) {
      this.form = { id: row.id, description: row.description, class_number: row.class_number || '', gds: row.gds, ads: row.ads, source: row.source };
      this.dialogError = '';
      this.dialog = true;
    },
    async save() {
      if (!this.form.description.trim()) return;
      this.saving = true;
      this.dialogError = '';
      try {
        const method = this.form.id ? 'PUT' : 'POST';
        const url = this.form.id ? `/api/asset-classes/${this.form.id}` : '/api/asset-classes';
        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/asset-classes/${target.id}`, { method: 'DELETE' });
        await this.load();
        this.$emit('updated');
      } catch (error) {
        this.error = error.message;
      }
    }
  }
};
</script>
