<template>
  <v-card class="span-12 panel-pad">
    <div class="toolbar-row mb-3">
      <div>
        <h2 class="section-title">Asset ID templates</h2>
        <p class="quiet text-body-2">
          Naming patterns for auto-assigning asset tags. Use <strong>#</strong> where the number goes — it is zero-padded to that
          width and increments automatically (e.g. <code>DT-######</code> → DT-000042). Assign a template to a category in
          <strong>Asset categories</strong> below; new assets in that category get the next tag automatically.
        </p>
      </div>
      <v-spacer />
      <v-btn color="primary" prepend-icon="mdi-plus" @click="openNew">New template</v-btn>
    </div>

    <DataTable
      :columns="columns"
      :rows="templates"
      row-key="id"
      :page-size="10"
      has-actions
      searchable
      search-placeholder="Filter templates"
      empty-text="No ID templates yet."
    >
      <template #cell-name="{ row }">
        <span class="font-weight-bold">{{ row.name }}</span>
      </template>
      <template #cell-pattern="{ row }"><code>{{ row.pattern }}</code></template>
      <template #cell-preview="{ row }"><code>{{ row.preview }}</code></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="480">
      <v-card>
        <v-card-title>{{ form.id ? 'Edit ID template' : 'New ID template' }}</v-card-title>
        <v-card-text>
          <v-text-field v-model="form.name" label="Template name" autofocus />
          <v-text-field
            v-model="form.pattern"
            label="Pattern"
            placeholder="DT-######"
            hint="Use # for the auto-incrementing number"
            persistent-hint
          />
          <v-text-field v-model.number="form.next_number" type="number" min="1" label="Next number" class="mt-2" />
          <v-alert type="info" variant="tonal" density="comfortable" class="mt-3">
            Next tag preview: <strong><code>{{ preview }}</code></strong>
          </v-alert>
          <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="!canSave" @click="save">Save</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Delete confirmation -->
    <v-dialog v-model="deleteDialog" max-width="500">
      <v-card>
        <v-card-title class="text-error">Delete ID template</v-card-title>
        <v-card-text>
          <p class="mb-3">Delete the template <strong>“{{ deleteTarget?.name }}”</strong>?</p>
          <v-alert
            :type="deleteTarget && deleteTarget.category_count ? 'warning' : 'info'"
            variant="tonal"
            density="comfortable"
            class="mb-3"
          >
            <template v-if="deleteTarget && deleteTarget.category_count">
              This template is assigned to <strong>{{ deleteTarget.category_count }}</strong>
              categor{{ deleteTarget.category_count === 1 ? 'y' : 'ies' }}.
            </template>
            <template v-else>This template is not assigned to any category.</template>
          </v-alert>
          <ul class="delete-impact">
            <li>Existing assets <strong>keep their current IDs</strong> — nothing is renamed.</li>
            <li>Affected categories are <strong>unassigned</strong>; new assets in them fall back to the default <code>MA-#####</code> sequence.</li>
          </ul>
        </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 template</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 { id: null, name: '', pattern: '', next_number: 1 };
}

export default {
  components: { DataTable },
  props: {
    token: { type: String, required: true }
  },
  emits: ['updated'],
  data() {
    return {
      templates: [],
      dialog: false,
      deleteDialog: false,
      deleteTarget: null,
      form: blankForm(),
      saving: false,
      error: '',
      dialogError: '',
      columns: [
        { key: 'name', label: 'Name' },
        { key: 'pattern', label: 'Pattern' },
        { key: 'preview', label: 'Next tag' },
        { key: 'next_number', label: 'Next #', format: 'number' },
        { key: 'category_count', label: 'Categories', format: 'number' }
      ]
    };
  },
  computed: {
    preview() {
      const pattern = String(this.form.pattern || '');
      const n = Math.max(1, Number(this.form.next_number) || 1);
      if (!pattern.includes('#')) return '—';
      return pattern.replace(/#+/, (hashes) => String(n).padStart(hashes.length, '0'));
    },
    canSave() {
      return Boolean(this.form.name.trim()) && String(this.form.pattern).includes('#');
    }
  },
  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/asset-id-templates')).json();
        this.templates = data.templates;
      } catch (error) {
        this.error = error.message;
      }
    },
    openNew() {
      this.form = blankForm();
      this.dialogError = '';
      this.dialog = true;
    },
    openEdit(row) {
      this.form = { id: row.id, name: row.name, pattern: row.pattern, next_number: row.next_number };
      this.dialogError = '';
      this.dialog = true;
    },
    async save() {
      if (!this.canSave) return;
      this.saving = true;
      this.dialogError = '';
      try {
        const method = this.form.id ? 'PUT' : 'POST';
        const url = this.form.id ? `/api/asset-id-templates/${this.form.id}` : '/api/asset-id-templates';
        await this.api(url, {
          method,
          body: JSON.stringify({ name: this.form.name.trim(), pattern: String(this.form.pattern).trim(), next_number: this.form.next_number })
        });
        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-id-templates/${target.id}`, { method: 'DELETE' });
        await this.load();
        this.$emit('updated');
      } catch (error) {
        this.error = error.message;
      }
    }
  }
};
</script>

<style scoped>
.delete-impact {
  padding-left: 20px;
  line-height: 1.6;
}
.delete-impact li {
  margin-bottom: 4px;
}
code {
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
  font-size: 0.85em;
  padding: 1px 5px;
  border-radius: 4px;
  background: rgba(var(--v-theme-on-surface), 0.08);
}
</style>
