<template>
  <div v-if="activeSection === 'accounting'" class="card">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
      <h2>Accounting</h2>
      <div style="display: flex; gap: 10px;">
        <button class="btn btn-primary" @click="$emit('add-journal-entry')">New Journal Entry</button>
        <button class="btn btn-success" @click="$emit('add-invoice')">Create Invoice</button>
        <input 
          type="text" 
          :value="searchTerm"
          @input="$emit('search', $event.target.value)"
          placeholder="Search..." 
          style="padding: 8px; border: 1px solid #ddd; border-radius: 4px;"
        >
      </div>
    </div>
    
    <!-- Accounting Dashboard -->
    <div class="accounting-dashboard">
      <div class="dashboard-cards">
        <div class="dashboard-card">
          <h3>Total Revenue</h3>
          <p class="amount">{{ formatCurrency(totalRevenue) }}</p>
        </div>
        <div class="dashboard-card">
          <h3>Total Expenses</h3>
          <p class="amount">{{ formatCurrency(totalExpenses) }}</p>
        </div>
        <div class="dashboard-card">
          <h3>Net Income</h3>
          <p class="amount" :class="{ 'negative': netIncome < 0 }">
            {{ formatCurrency(netIncome) }}
          </p>
        </div>
        <div class="dashboard-card">
          <h3>Journal Entries</h3>
          <p class="count">{{ journalEntries.length }}</p>
        </div>
      </div>
    </div>
    
    <!-- Tabs for different accounting sections -->
    <div class="accounting-tabs">
      <button 
        :class="['tab-btn', { active: activeTab === 'journal' }]" 
        @click="activeTab = 'journal'"
      >
        Journal Entries
      </button>
      <button 
        :class="['tab-btn', { active: activeTab === 'transactions' }]" 
        @click="activeTab = 'transactions'"
      >
        Transactions
      </button>
      <button 
        :class="['tab-btn', { active: activeTab === 'invoices' }]" 
        @click="activeTab = 'invoices'"
      >
        Invoices
      </button>
    </div>
    
    <!-- Journal Entries Tab -->
    <div v-if="activeTab === 'journal'" class="tab-content">
      <div v-if="journalEntriesLoading" class="loading">
        Loading journal entries...
      </div>
      
      <div v-else-if="journalEntries.length === 0" class="loading">
        No journal entries found. Create your first journal entry!
      </div>
      
      <table v-else class="table">
        <thead>
          <tr>
            <th>Entry #</th>
            <th>Date</th>
            <th>Description</th>
            <th>Reference</th>
            <th>Debits</th>
            <th>Credits</th>
            <th>Balance</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="entry in journalEntries" :key="entry.id">
            <td>{{ entry.entry_number }}</td>
            <td>{{ formatDate(entry.entry_date) }}</td>
            <td>{{ entry.description }}</td>
            <td>{{ entry.reference_number || '-' }}</td>
            <td class="currency">{{ formatCurrency(getEntryDebits(entry)) }}</td>
            <td class="currency">{{ formatCurrency(getEntryCredits(entry)) }}</td>
            <td class="currency">{{ formatCurrency(getEntryBalance(entry)) }}</td>
            <td>
              <div class="actions">
                <button class="btn btn-primary" @click="$emit('view-journal-entry', entry)">View</button>
                <button class="btn btn-warning" @click="$emit('edit-journal-entry', entry)">Edit</button>
                <button class="btn btn-danger" @click="$emit('delete-journal-entry', entry.id)">Delete</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- Transactions Tab -->
    <div v-if="activeTab === 'transactions'" class="tab-content">
      <div v-if="transactionsLoading" class="loading">
        Loading transactions...
      </div>
      
      <div v-else-if="transactions.length === 0" class="loading">
        No transactions found.
      </div>
      
      <table v-else class="table">
        <thead>
          <tr>
            <th>Date</th>
            <th>Account</th>
            <th>Description</th>
            <th>Debit</th>
            <th>Credit</th>
            <th>VAT %</th>
            <th>Balance</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="transaction in transactions" :key="transaction.id">
            <td>{{ formatDate(transaction.created_at) }}</td>
            <td>{{ transaction.account_name || 'Account #' + transaction.account_id }}</td>
            <td>{{ transaction.description }}</td>
            <td class="currency">{{ formatCurrency(transaction.debit_amount) }}</td>
            <td class="currency">{{ formatCurrency(transaction.credit_amount) }}</td>
            <td class="vat-percentage">{{ formatVAT(transaction.vat_percentage) }}</td>
            <td class="currency">{{ formatCurrency(transaction.amount) }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- Invoices Tab -->
    <div v-if="activeTab === 'invoices'" class="tab-content">
      <div v-if="invoicesLoading" class="loading">
        Loading invoices...
      </div>
      
      <div v-else-if="invoices.length === 0" class="loading">
        No invoices found. Create your first invoice!
      </div>
      
      <table v-else class="table">
        <thead>
          <tr>
            <th>Invoice #</th>
            <th>Client</th>
            <th>Issue Date</th>
            <th>Due Date</th>
            <th>Status</th>
            <th>Total</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="invoice in invoices" :key="invoice.id">
            <td>{{ invoice.invoice_number }}</td>
            <td>{{ invoice.client_name }}</td>
            <td>{{ formatDateTime(invoice.issue_date) }}</td>
            <td>{{ formatDateTime(invoice.due_date) }}</td>
            <td v-html="invoice.getStatusBadge()"></td>
            <td>{{ formatCurrency(invoice.total_amount) }}</td>
            <td>
              <div class="actions">
                <button class="btn btn-primary" @click="$emit('view-invoice', invoice)">View</button>
                <button class="btn btn-warning" @click="$emit('edit-invoice', invoice)">Edit</button>
                <button class="btn btn-danger" @click="$emit('delete-invoice', invoice.id)">Delete</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import { formatCurrency, formatDateTime } from '../../utils/locale.js'

export default {
  name: 'AccountingSection',
  props: {
    activeSection: {
      type: String,
      required: true
    },
    invoices: {
      type: Array,
      required: true
    },
    invoicesLoading: {
      type: Boolean,
      default: false
    },
    journalEntries: {
      type: Array,
      required: true
    },
    journalEntriesLoading: {
      type: Boolean,
      default: false
    },
    transactions: {
      type: Array,
      required: true
    },
    transactionsLoading: {
      type: Boolean,
      default: false
    },
    searchTerm: {
      type: String,
      default: ''
    }
  },
  emits: [
    'add-invoice', 'view-invoice', 'edit-invoice', 'delete-invoice', 'search-invoices',
    'add-journal-entry', 'view-journal-entry', 'edit-journal-entry', 'delete-journal-entry',
    'search'
  ],
  data() {
    return {
      activeTab: 'journal'
    }
  },
  computed: {
    totalRevenue() {
      return this.transactions
        .filter(t => t.credit_amount > 0)
        .reduce((sum, t) => sum + parseFloat(t.credit_amount || 0), 0)
    },
    totalExpenses() {
      return this.transactions
        .filter(t => t.debit_amount > 0)
        .reduce((sum, t) => sum + parseFloat(t.debit_amount || 0), 0)
    },
    netIncome() {
      return this.totalRevenue - this.totalExpenses
    }
  },
  methods: {
    formatCurrency,
    formatDateTime,
    formatVAT(percentage) {
      if (percentage === null || percentage === undefined || percentage === 0) {
        return '-'
      }
      return `${parseFloat(percentage).toFixed(2)}%`
    },
    getEntryDebits(entry) {
      if (!entry.transactions) return 0;
      return entry.transactions
        .filter(t => t.debit_amount > 0)
        .reduce((sum, t) => sum + parseFloat(t.debit_amount || 0), 0)
    },
    getEntryCredits(entry) {
      if (!entry.transactions) return 0;
      return entry.transactions
        .filter(t => t.credit_amount > 0)
        .reduce((sum, t) => sum + parseFloat(t.credit_amount || 0), 0)
    },
    getEntryBalance(entry) {
      return this.getEntryCredits(entry) - this.getEntryDebits(entry)
    }
  }
}
</script>

<style scoped>
.loading {
  text-align: center;
  padding: 40px;
  color: #333;
}

.accounting-dashboard {
  margin-bottom: 30px;
}

.dashboard-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.dashboard-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.dashboard-card:nth-child(2) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.dashboard-card:nth-child(3) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.dashboard-card:nth-child(4) {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.dashboard-card h3 {
  margin: 0 0 10px 0;
  font-size: 14px;
  font-weight: 500;
  opacity: 0.9;
}

.dashboard-card .amount {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
}

.dashboard-card .count {
  margin: 0;
  font-size: 32px;
  font-weight: 700;
}

.dashboard-card .amount.negative {
  color: #ff6b6b;
}

.accounting-tabs {
  display: flex;
  border-bottom: 2px solid #e9ecef;
  margin-bottom: 20px;
}

.tab-btn {
  background: none;
  border: none;
  padding: 12px 24px;
  cursor: pointer;
  font-size: 16px;
  color: #6c757d;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.tab-btn:hover {
  color: #495057;
}

.tab-btn.active {
  color: #007bff;
  border-bottom-color: #007bff;
  font-weight: 600;
}

.tab-content {
  min-height: 200px;
}

.actions {
  display: flex;
  gap: 5px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.table th,
.table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
  color: #333;
}

.table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #495057;
}

.table tbody tr:hover {
  background-color: #f8f9fa;
}

.currency {
  text-align: right;
  font-family: 'Courier New', monospace;
  font-weight: 600;
}

.vat-percentage {
  text-align: center;
  font-weight: 600;
  color: #495057;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.2s ease;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-success:hover {
  background-color: #218838;
}

.btn-warning {
  background-color: #ffc107;
  color: #212529;
}

.btn-warning:hover {
  background-color: #e0a800;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #c82333;
}
</style>
