<template>
  <section class="content-grid">
    <!-- Book configuration -->
    <v-card class="span-12 panel-pad">
      <div class="toolbar-row mb-1">
        <h2 class="section-title">Books</h2>
        <v-spacer />
        <v-btn color="primary" size="small" prepend-icon="mdi-plus" @click="openNewBook">New book</v-btn>
      </div>
      <p class="quiet text-body-2 mb-3">
        Configure each set of books, assign the depreciation rule set it should use, and set entry defaults. Add user-defined
        books for additional reporting scenarios. View each book’s general ledger and journal entries under
        <strong>Financial → GL and Journals</strong>.
      </p>
      <div style="overflow-x:auto">
        <table class="asset-table">
          <thead>
            <tr>
              <th>Book</th>
              <th>Type</th>
              <th>Tax rule set</th>
              <th>Default method</th>
              <th>Convention</th>
              <th>Assets</th>
              <th>Enabled</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="book in books" :key="book.id">
              <td>
                <div class="font-weight-bold">{{ book.code }}<v-chip v-if="book.is_primary" size="x-small" color="primary" variant="tonal" class="ml-2">primary</v-chip></div>
                <v-text-field v-model="book.name" density="compact" hide-details variant="plain" />
              </td>
              <td style="min-width:140px">
                <v-select v-model="book.book_type" :items="bookTypeItems" item-title="title" item-value="value" density="compact" hide-details />
              </td>
              <td style="min-width:220px">
                <v-select
                  v-model="book.tax_rule_set_id"
                  :items="ruleSetItems"
                  item-title="title"
                  item-value="value"
                  density="compact"
                  hide-details
                  clearable
                  placeholder="Active set"
                />
              </td>
              <td style="min-width:220px">
                <v-select v-model="book.default_method" :items="methodItems" item-title="title" item-value="value" density="compact" hide-details />
              </td>
              <td style="min-width:160px">
                <v-select v-model="book.default_convention" :items="conventionItems" item-title="title" item-value="value" density="compact" hide-details />
              </td>
              <td>{{ book.asset_count }}</td>
              <td><v-switch v-model="book.enabled" color="primary" density="compact" hide-details /></td>
              <td class="text-right" style="white-space:nowrap">
                <v-btn size="small" color="primary" variant="tonal" prepend-icon="mdi-content-save" :loading="savingId === book.id" @click="save(book)">Save</v-btn>
                <v-btn
                  v-if="!book.is_primary && book.book_type !== 'maintenance'"
                  icon="mdi-delete-outline"
                  size="small"
                  variant="text"
                  color="error"
                  class="ml-1"
                  @click="removeBook(book)"
                />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <v-alert v-if="error" type="error" density="compact" class="mt-3">{{ error }}</v-alert>
      <v-alert v-if="message" type="success" density="compact" class="mt-3">{{ message }}</v-alert>
    </v-card>

    <v-dialog v-model="newBookDialog" max-width="560">
      <v-card>
        <v-card-title>New book</v-card-title>
        <v-card-text>
          <div class="form-grid">
            <v-text-field v-model="newBook.code" label="Code" hint="Short unique code, e.g. IFRS" persistent-hint />
            <v-text-field v-model="newBook.name" label="Name" />
            <v-select v-model="newBook.book_type" :items="bookTypeItems" item-title="title" item-value="value" label="Type" />
            <v-select v-model="newBook.tax_rule_set_id" :items="ruleSetItems" item-title="title" item-value="value" clearable placeholder="Active set" label="Tax rule set" />
            <v-select v-model="newBook.default_method" :items="methodItems" item-title="title" item-value="value" label="Default method" />
            <v-select v-model="newBook.default_convention" :items="conventionItems" item-title="title" item-value="value" label="Default convention" />
            <v-textarea v-model="newBook.description" class="full" label="Description" rows="2" />
            <v-switch v-model="newBook.enabled" label="Enabled (apply to assets)" color="primary" density="compact" hide-details />
          </div>
          <v-alert v-if="newBookError" type="error" density="compact" class="mt-2">{{ newBookError }}</v-alert>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="newBookDialog = false">Cancel</v-btn>
          <v-btn color="primary" prepend-icon="mdi-content-save" :disabled="!newBook.code" :loading="creating" @click="createBook">Create book</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </section>
</template>

<script>
import { apiRequest } from '../services/api';
import { conventionItems } from '../constants';

export default {
  props: {
    token: { type: String, required: true },
    methodItems: { type: Array, default: () => [] }
  },
  emits: ['updated'],
  data() {
    return {
      conventionItems,
      bookTypeItems: [
        { title: 'Financial', value: 'financial' },
        { title: 'Tax', value: 'tax' },
        { title: 'Internal', value: 'internal' }
      ],
      books: [],
      ruleSets: [],
      savingId: null,
      error: '',
      message: '',
      newBookDialog: false,
      newBookError: '',
      creating: false,
      newBook: this.blankBook()
    };
  },
  computed: {
    ruleSetItems() {
      return this.ruleSets.map((set) => ({ title: `${set.name} · ${set.version}`, value: set.id }));
    }
  },
  mounted() {
    this.load();
  },
  methods: {
    blankBook() {
      return { code: '', name: '', description: '', book_type: 'internal', tax_rule_set_id: null, default_method: 'straight_line', default_convention: 'half_year', enabled: true };
    },
    openNewBook() {
      this.newBook = this.blankBook();
      this.newBookError = '';
      this.newBookDialog = true;
    },
    async createBook() {
      this.creating = true;
      this.newBookError = '';
      try {
        await this.api('/api/books', { method: 'POST', body: JSON.stringify(this.newBook) });
        this.newBookDialog = false;
        await this.load();
        this.$emit('updated');
      } catch (error) {
        this.newBookError = error.message;
      } finally {
        this.creating = false;
      }
    },
    async removeBook(book) {
      this.error = '';
      if (!window.confirm(`Delete book "${book.code}"?`)) return;
      try {
        await this.api(`/api/books/${book.id}`, { method: 'DELETE' });
        await this.load();
        this.$emit('updated');
      } catch (error) {
        this.error = error.message;
      }
    },
    async api(path, options = {}) {
      return apiRequest(path, this.token, options);
    },
    async load() {
      const data = await (await this.api('/api/books')).json();
      this.books = data.books;
      this.ruleSets = data.ruleSets;
    },
    async save(book) {
      this.savingId = book.id;
      this.error = '';
      this.message = '';
      try {
        await this.api(`/api/books/${book.id}`, {
          method: 'PUT',
          body: JSON.stringify({
            name: book.name,
            book_type: book.book_type,
            enabled: book.enabled,
            tax_rule_set_id: book.tax_rule_set_id,
            default_method: book.default_method,
            default_convention: book.default_convention
          })
        });
        this.message = `${book.code} saved.`;
        this.$emit('updated');
      } catch (error) {
        this.error = error.message;
      } finally {
        this.savingId = null;
      }
    }
  }
};
</script>
