<template>
  <v-card class="span-12 panel-pad">
    <div class="toolbar-row mb-3">
      <div>
        <h2 class="section-title">Companies</h2>
        <p class="quiet text-body-2">
          Each company keeps its own assets, books, general ledger, PM plans, and alerts. Switch the active company
          from the top bar. Disposing a company archives it (history is preserved) and removes it from the switcher.
        </p>
      </div>
      <v-spacer />
      <v-btn color="primary" prepend-icon="mdi-domain-plus" @click="openNew">New company</v-btn>
    </div>

    <DataTable
      :columns="columns"
      :rows="companies"
      row-key="id"
      :page-size="10"
      has-actions
      searchable
      search-placeholder="Filter companies"
      empty-text="No companies."
    >
      <template #cell-name="{ row }">
        <span class="font-weight-bold">{{ row.name }}</span>
      </template>
      <template #cell-status="{ row }">
        <v-chip size="x-small" :color="row.status === 'active' ? 'success' : 'error'" variant="tonal">{{ row.status }}</v-chip>
      </template>
      <template #cell-base_currency="{ row }">{{ row.base_currency || 'USD' }}</template>
      <template #actions="{ row }">
        <v-btn icon="mdi-pencil" size="small" variant="text" @click="openEdit(row)" />
        <v-btn v-if="row.status === 'active'" icon="mdi-archive-arrow-down-outline" size="small" variant="text" color="error" title="Dispose / archive" @click="confirmDispose(row)" />
        <v-btn v-else icon="mdi-restore" size="small" variant="text" color="success" title="Restore" @click="restore(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 company' : 'New company' }}</v-card-title>
        <v-card-text>
          <div class="form-grid">
            <v-text-field v-model="form.name" class="full" label="Company name *" autofocus />
            <v-text-field v-model="form.legal_name" class="full" label="Legal name" />
            <v-text-field v-model="form.federal_tax_id" label="Federal tax ID (EIN)" />
            <v-text-field v-model="form.state_tax_id" label="State tax ID" />
            <v-text-field v-model="form.local_tax_id" label="Local tax ID (optional)" />
            <v-text-field v-model="form.base_currency" label="Base currency" placeholder="USD" />
            <v-select v-model.number="form.fiscal_year_end_month" :items="monthItems" item-title="title" item-value="value" label="Fiscal year-end month" />
          </div>
          <v-alert v-if="!form.id" type="info" variant="tonal" density="compact" class="mt-2">
            A new company starts with the standard book set (GAAP, Federal, State, AMT, ACE, User, PM).
          </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="!form.name.trim()" @click="save">Save company</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Dispose confirmation -->
    <v-dialog v-model="disposeDialog" max-width="500">
      <v-card>
        <v-card-title class="text-error">Dispose company</v-card-title>
        <v-card-text>
          <p class="mb-3">Archive <strong>“{{ disposeTarget?.name }}”</strong>?</p>
          <v-alert type="info" variant="tonal" density="comfortable" class="mb-3">
            Its assets, books, GL, PM plans, and alerts are <strong>kept</strong> for audit and reporting, but the company
            is hidden from the switcher and can no longer be selected for new work. You can restore it later.
          </v-alert>
          <v-text-field v-model="disposeReason" label="Reason (optional)" density="compact" />
          <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="disposeDialog = false">Cancel</v-btn>
          <v-btn color="error" prepend-icon="mdi-archive-arrow-down-outline" @click="performDispose">Dispose company</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-card>
</template>

<script>
import DataTable from './DataTable.vue';
import { apiRequest } from '../services/api';

// Admin company management (Admin → Application Configuration). Lists every company including disposed
// ones (?includeDisposed=1), supports add/edit, and soft dispose/restore. Emits `updated` so App.vue
// can refresh the top-bar company switcher.

function blankCompany() {
  return { id: null, name: '', legal_name: '', federal_tax_id: '', state_tax_id: '', local_tax_id: '', base_currency: 'USD', fiscal_year_end_month: 12 };
}

export default {
  components: { DataTable },
  props: {
    token: { type: String, required: true }
  },
  emits: ['updated'],
  data() {
    return {
      companies: [],
      dialog: false,
      disposeDialog: false,
      disposeTarget: null,
      disposeReason: '',
      form: blankCompany(),
      saving: false,
      error: '',
      dialogError: '',
      monthItems: Array.from({ length: 12 }, (_, i) => ({ title: new Date(2000, i, 1).toLocaleString('en-US', { month: 'long' }), value: i + 1 })),
      columns: [
        { key: 'name', label: 'Company' },
        { key: 'legal_name', label: 'Legal name' },
        { key: 'federal_tax_id', label: 'Federal tax ID' },
        { key: 'base_currency', label: 'Currency' },
        { key: 'status', label: 'Status', sortable: false }
      ]
    };
  },
  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/entities?includeDisposed=1')).json();
        this.companies = data.entities;
      } catch (error) {
        this.error = error.message;
      }
    },
    openNew() {
      this.form = blankCompany();
      this.dialogError = '';
      this.dialog = true;
    },
    openEdit(row) {
      this.form = { id: row.id, name: row.name, legal_name: row.legal_name || '', federal_tax_id: row.federal_tax_id || '', state_tax_id: row.state_tax_id || '', local_tax_id: row.local_tax_id || '', base_currency: row.base_currency || 'USD', fiscal_year_end_month: row.fiscal_year_end_month || 12 };
      this.dialogError = '';
      this.dialog = true;
    },
    async save() {
      this.saving = true;
      this.dialogError = '';
      try {
        const method = this.form.id ? 'PUT' : 'POST';
        const url = this.form.id ? `/api/entities/${this.form.id}` : '/api/entities';
        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;
      }
    },
    confirmDispose(row) {
      this.disposeTarget = row;
      this.disposeReason = '';
      this.dialogError = '';
      this.disposeDialog = true;
    },
    async performDispose() {
      this.dialogError = '';
      try {
        await this.api(`/api/entities/${this.disposeTarget.id}/dispose`, { method: 'POST', body: JSON.stringify({ reason: this.disposeReason || null }) });
        this.disposeDialog = false;
        await this.load();
        this.$emit('updated');
      } catch (error) {
        this.dialogError = error.message;
      }
    },
    async restore(row) {
      this.error = '';
      try {
        await this.api(`/api/entities/${row.id}/restore`, { method: 'POST', body: JSON.stringify({}) });
        await this.load();
        this.$emit('updated');
      } catch (error) {
        this.error = error.message;
      }
    }
  }
};
</script>
