<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.</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>

    <!-- General ledger -->
    <v-card class="span-12 panel-pad">
      <div class="toolbar-row mb-3">
        <h2 class="section-title">General ledger</h2>
        <v-spacer />
        <v-select v-model="ledgerBook" :items="bookCodeItems" label="Book" density="compact" hide-details style="max-width:180px" @update:model-value="loadLedger" />
        <v-text-field v-model.number="ledgerYear" type="number" label="Year" density="compact" hide-details style="max-width:120px" @update:model-value="loadLedger" />
        <v-menu>
          <template #activator="{ props }">
            <v-btn v-bind="props" color="secondary" size="small" prepend-icon="mdi-download">Export</v-btn>
          </template>
          <v-list density="compact">
            <v-list-item v-for="format in ['pdf', 'xlsx', 'csv']" :key="format" :title="format.toUpperCase()" @click="exportLedger(format)" />
          </v-list>
        </v-menu>
      </div>

      <div v-if="ledger">
        <div v-if="ledger.kind === 'maintenance'" class="ledger-summary mb-4">
          <div class="ledger-chip"><span class="quiet">Assets serviced</span><strong>{{ ledger.summary.assets }}</strong></div>
          <div class="ledger-chip"><span class="quiet">Services ({{ ledger.year }})</span><strong>{{ ledger.summary.completions }}</strong></div>
          <div class="ledger-chip"><span class="quiet">Total PM spend</span><strong>{{ currency(ledger.summary.cost) }}</strong></div>
        </div>
        <div v-else class="ledger-summary mb-4">
          <div class="ledger-chip"><span class="quiet">Assets</span><strong>{{ ledger.summary.assets }}</strong></div>
          <div class="ledger-chip"><span class="quiet">Cost</span><strong>{{ currency(ledger.summary.cost) }}</strong></div>
          <div class="ledger-chip"><span class="quiet">Accumulated depr.</span><strong>{{ currency(ledger.summary.accumulated) }}</strong></div>
          <div class="ledger-chip"><span class="quiet">Net book value</span><strong>{{ currency(ledger.summary.nbv) }}</strong></div>
          <div class="ledger-chip"><span class="quiet">{{ ledger.year }} depreciation</span><strong>{{ currency(ledger.summary.depreciation) }}</strong></div>
          <div class="ledger-chip"><span class="quiet">Rule set</span><strong>{{ ledger.rule_set.name || 'Active set' }}</strong></div>
        </div>

        <div style="overflow-x:auto">
          <table class="asset-table">
            <thead>
              <tr><th>GL account</th><th>Account type</th><th class="text-right">Debit</th><th class="text-right">Credit</th></tr>
            </thead>
            <tbody>
              <tr v-for="(line, index) in ledger.accounts" :key="index">
                <td class="font-weight-bold">{{ line.account }}</td>
                <td>{{ line.type }}</td>
                <td class="text-right">{{ line.debit ? currency(line.debit) : '' }}</td>
                <td class="text-right">{{ line.credit ? currency(line.credit) : '' }}</td>
              </tr>
              <tr v-if="!ledger.accounts.length"><td colspan="4" class="quiet">No postings for this book and year.</td></tr>
            </tbody>
            <tfoot>
              <tr>
                <td class="font-weight-bold" colspan="2">Totals</td>
                <td class="text-right font-weight-bold">{{ currency(ledger.accountTotals.debit) }}</td>
                <td class="text-right font-weight-bold">{{ currency(ledger.accountTotals.credit) }}</td>
              </tr>
            </tfoot>
          </table>
        </div>

        <v-expansion-panels class="mt-4" variant="accordion">
          <v-expansion-panel title="Asset detail">
            <v-expansion-panel-text>
              <DataTable
                :columns="detailColumns"
                :rows="ledger.assets"
                row-key="asset_id"
                searchable
                search-placeholder="Filter assets"
                empty-text="No assets in this book."
              >
                <template #cell-asset_id="{ row }">
                  <span class="font-weight-bold">{{ row.asset_id }}</span>
                </template>
              </DataTable>
            </v-expansion-panel-text>
          </v-expansion-panel>
        </v-expansion-panels>
      </div>
      <div v-else class="quiet text-body-2">Select a book to view its general ledger.</div>
    </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 DataTable from '../components/DataTable.vue';
import { apiRequest, saveBlob } from '../services/api';
import { currency } from '../utils/format';
import { conventionItems } from '../constants';

export default {
  components: { DataTable },
  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: [],
      ledger: null,
      ledgerBook: 'GAAP',
      ledgerYear: new Date().getFullYear(),
      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 }));
    },
    bookCodeItems() {
      return this.books.map((book) => book.code);
    },
    detailColumns() {
      const year = this.ledger?.year || this.ledgerYear;
      if (this.ledger?.kind === 'maintenance') {
        return [
          { key: 'asset_id', label: 'Asset ID' },
          { key: 'description', label: 'Description' },
          { key: 'completions', label: 'Services', format: 'number' },
          { key: 'last_service', label: 'Last service', format: 'date' },
          { key: 'cost', label: `${year} PM cost`, format: 'currency' }
        ];
      }
      return [
        { key: 'asset_id', label: 'Asset ID' },
        { key: 'description', label: 'Description' },
        { key: 'asset_account', label: 'Asset acct' },
        { key: 'expense_account', label: 'Expense acct' },
        { key: 'cost', label: 'Cost', format: 'currency' },
        { key: 'depreciation', label: `${year} depr.`, format: 'currency' },
        { key: 'accumulated', label: 'Accum.', format: 'currency' },
        { key: 'nbv', label: 'NBV', format: 'currency' }
      ];
    }
  },
  mounted() {
    this.load();
  },
  methods: {
    currency,
    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;
      if (this.books.length) {
        if (!this.books.some((book) => book.code === this.ledgerBook)) this.ledgerBook = this.books[0].code;
        this.loadLedger();
      }
    },
    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');
        if (book.code === this.ledgerBook) this.loadLedger();
      } catch (error) {
        this.error = error.message;
      } finally {
        this.savingId = null;
      }
    },
    async loadLedger() {
      if (!this.ledgerBook) return;
      this.error = '';
      try {
        const data = await (await this.api(`/api/books/${this.ledgerBook}/ledger?year=${this.ledgerYear}`)).json();
        this.ledger = data.ledger;
      } catch (error) {
        this.error = error.message;
      }
    },
    async exportLedger(format) {
      const blob = await (await this.api(`/api/books/${this.ledgerBook}/ledger/export`, {
        method: 'POST',
        body: JSON.stringify({ year: this.ledgerYear, format })
      })).blob();
      saveBlob(blob, `deprecore-${this.ledgerBook}-ledger-${this.ledgerYear}.${format}`);
    }
  }
};
</script>

<style scoped>
.ledger-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
.ledger-chip {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 140px;
  padding: 10px 14px;
  border: 1px solid rgba(128, 128, 128, 0.25);
  border-radius: 8px;
}
.ledger-chip strong {
  font-size: 1.05rem;
}
</style>
