<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import {
  accountingService,
  type AccountTransaction,
  type AccountingSummary,
  type Expense,
  type ExpenseCategory,
  type FinancialAccount,
  type PaginationMeta,
} from '@/modules/accounting/services/accountingService'
import { getApiErrorMessage } from '@/services/api'
import { useCompanyContextStore } from '@/stores/companyContext'

const today = new Date()
const firstDay = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().slice(0, 10)
const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().slice(0, 10)

const startDate = ref(firstDay)
const endDate = ref(lastDay)
const categories = ref<ExpenseCategory[]>([])
const accounts = ref<FinancialAccount[]>([])
const transactions = ref<AccountTransaction[]>([])
const expenses = ref<Expense[]>([])
const summary = ref<AccountingSummary | null>(null)
const meta = ref<PaginationMeta | null>(null)
const transactionMeta = ref<PaginationMeta | null>(null)
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const success = ref('')
const currentCompanyId = ref(localStorage.getItem('current_company_id') || '')
const companyContext = useCompanyContextStore()
const editingExpense = ref<Expense | null>(null)
const editingAccount = ref<FinancialAccount | null>(null)
const editingCategory = ref<ExpenseCategory | null>(null)

const filters = reactive({
  search: '',
  expense_category_id: '',
  financial_account_id: '',
  payment_method: '',
  status: 'recorded',
  date_from: firstDay,
  date_to: lastDay,
  page: 1,
  per_page: 10,
})

const transactionFilters = reactive({
  financial_account_id: '',
  type: '',
  direction: '',
  date_from: firstDay,
  date_to: lastDay,
  page: 1,
  per_page: 8,
})

const expenseForm = reactive({
  expense_category_id: '',
  financial_account_id: '',
  expense_date: today.toISOString().slice(0, 10),
  description: '',
  amount: 0,
  payment_method: 'cash',
  vendor: '',
  reference: '',
  notes: '',
  status: 'recorded',
})

const categoryForm = reactive({
  name: '',
})

const categoryEditForm = reactive({
  name: '',
  status: 'active',
})

const accountForm = reactive({
  name: '',
  type: 'cash',
  opening_balance: 0,
})

const accountEditForm = reactive({
  name: '',
  type: 'cash',
  opening_balance: 0,
  status: 'active',
})

const transactionForm = reactive({
  financial_account_id: '',
  transaction_date: today.toISOString().slice(0, 10),
  type: 'income',
  direction: 'inflow',
  amount: 0,
  description: '',
  reference: '',
  notes: '',
})

const transferForm = reactive({
  from_account_id: '',
  to_account_id: '',
  transaction_date: today.toISOString().slice(0, 10),
  amount: 0,
  description: '',
  reference: '',
  notes: '',
})

const profitClass = computed(() => (Number(summary.value?.net_profit || 0) >= 0 ? 'text-[#087443]' : 'text-danger'))
const formTitle = computed(() => (editingExpense.value ? 'Edit Expense' : 'Record Expense'))
const formButtonLabel = computed(() => (editingExpense.value ? 'Update Expense' : 'Save Expense'))
const totalAccountBalance = computed(() => accounts.value.reduce((total, account) => total + Number(account.current_balance || 0), 0))
const canManageAccounting = computed(() => companyContext.hasPermission('accounting.manage'))

function money(value: string | number | undefined) {
  return Number(value || 0).toFixed(2)
}

function clearMessages() {
  error.value = ''
  success.value = ''
}

function setError(apiError: unknown, fallback: string) {
  success.value = ''
  error.value = getApiErrorMessage(apiError, fallback)
}

function setSuccess(message: string) {
  error.value = ''
  success.value = message
}

function statusClass(status: string) {
  return status === 'active' || status === 'recorded' ? 'status-pill' : 'status-pill off'
}

function directionClass(direction: string) {
  return direction === 'inflow' ? 'status-pill' : 'status-pill warn'
}

function validateExpenseDateRange() {
  if (filters.date_from && filters.date_to && filters.date_from > filters.date_to) {
    error.value = 'Expense date range is invalid.'
    success.value = ''
    return false
  }

  return true
}

function validateLedgerDateRange() {
  if (transactionFilters.date_from && transactionFilters.date_to && transactionFilters.date_from > transactionFilters.date_to) {
    error.value = 'Ledger date range is invalid.'
    success.value = ''
    return false
  }

  return true
}

function cleanFilters() {
  return {
    search: filters.search || undefined,
    expense_category_id: filters.expense_category_id ? Number(filters.expense_category_id) : undefined,
    financial_account_id: filters.financial_account_id ? Number(filters.financial_account_id) : undefined,
    payment_method: filters.payment_method || undefined,
    status: filters.status || undefined,
    date_from: filters.date_from || undefined,
    date_to: filters.date_to || undefined,
    page: filters.page,
    per_page: filters.per_page,
  }
}

function cleanTransactionFilters() {
  return {
    financial_account_id: transactionFilters.financial_account_id ? Number(transactionFilters.financial_account_id) : undefined,
    type: transactionFilters.type || undefined,
    direction: transactionFilters.direction || undefined,
    date_from: transactionFilters.date_from || undefined,
    date_to: transactionFilters.date_to || undefined,
    page: transactionFilters.page,
    per_page: transactionFilters.per_page,
  }
}

async function load() {
  if (!currentCompanyId.value) {
    error.value = 'Select a company workspace first.'
    return
  }

  loading.value = true
  clearMessages()

  try {
    const [summaryData, categoryData, accountData, expenseData, transactionData] = await Promise.all([
      accountingService.summary(startDate.value, endDate.value),
      accountingService.categories(),
      accountingService.accounts(),
      accountingService.expenses(cleanFilters()),
      accountingService.transactions(cleanTransactionFilters()),
    ])

    summary.value = summaryData
    categories.value = categoryData
    accounts.value = accountData
    expenses.value = expenseData.data
    meta.value = expenseData.meta
    transactions.value = transactionData.data
    transactionMeta.value = transactionData.meta
  } catch (apiError) {
    setError(apiError, 'Unable to load finance data.')
  } finally {
    loading.value = false
  }
}

async function applyTransactionFilters() {
  if (!validateLedgerDateRange()) {
    return
  }

  transactionFilters.page = 1
  await load()
}

async function goToTransactionPage(page: number) {
  transactionFilters.page = Math.min(Math.max(page, 1), transactionMeta.value?.last_page || 1)
  await load()
}

async function changeTransactionPerPage() {
  transactionFilters.page = 1
  await load()
}

async function exportTransactions() {
  if (!validateLedgerDateRange()) {
    return
  }

  clearMessages()

  try {
    const blob = await accountingService.exportTransactionsCsv(cleanTransactionFilters())
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'accounting-ledger.csv'
    link.click()
    window.setTimeout(() => window.URL.revokeObjectURL(url), 60_000)
    setSuccess('Ledger export is ready.')
  } catch (apiError) {
    setError(apiError, 'Unable to export ledger.')
  }
}

async function createAccount() {
  if (!accountForm.name.trim()) {
    return
  }

  saving.value = true
  clearMessages()

  try {
    await accountingService.createAccount({
      name: accountForm.name.trim(),
      type: accountForm.type,
      opening_balance: Number(accountForm.opening_balance || 0),
    })
    accountForm.name = ''
    accountForm.opening_balance = 0
    await load()
    setSuccess('Financial account created.')
  } catch (apiError) {
    setError(apiError, 'Unable to create financial account.')
  } finally {
    saving.value = false
  }
}

function startAccountEdit(account: FinancialAccount) {
  editingAccount.value = account
  accountEditForm.name = account.name
  accountEditForm.type = account.type
  accountEditForm.opening_balance = Number(account.opening_balance)
  accountEditForm.status = account.status
}

function cancelAccountEdit() {
  editingAccount.value = null
  accountEditForm.name = ''
  accountEditForm.type = 'cash'
  accountEditForm.opening_balance = 0
  accountEditForm.status = 'active'
}

async function updateAccount() {
  if (!editingAccount.value || !accountEditForm.name.trim()) {
    return
  }

  saving.value = true
  clearMessages()

  try {
    await accountingService.updateAccount(editingAccount.value, {
      name: accountEditForm.name.trim(),
      type: accountEditForm.type,
      opening_balance: Number(accountEditForm.opening_balance || 0),
      status: accountEditForm.status,
    })
    cancelAccountEdit()
    await load()
    setSuccess('Financial account updated.')
  } catch (apiError) {
    setError(apiError, 'Unable to update financial account.')
  } finally {
    saving.value = false
  }
}

async function deactivateAccount(account: FinancialAccount) {
  saving.value = true
  clearMessages()

  try {
    await accountingService.updateAccount(account, { status: 'inactive' })
    if (editingAccount.value?.id === account.id) {
      cancelAccountEdit()
    }
    await load()
    setSuccess('Financial account deactivated.')
  } catch (apiError) {
    setError(apiError, 'Unable to deactivate financial account.')
  } finally {
    saving.value = false
  }
}

async function createTransaction() {
  if (!transactionForm.financial_account_id) {
    error.value = 'Select a financial account first.'
    success.value = ''
    return
  }

  saving.value = true
  clearMessages()

  try {
    await accountingService.createTransaction({
      financial_account_id: Number(transactionForm.financial_account_id),
      transaction_date: transactionForm.transaction_date,
      type: transactionForm.type,
      direction: transactionForm.direction,
      amount: Number(transactionForm.amount),
      description: transactionForm.description,
      reference: transactionForm.reference || null,
      notes: transactionForm.notes || null,
    })
    transactionForm.amount = 0
    transactionForm.description = ''
    transactionForm.reference = ''
    transactionForm.notes = ''
    await load()
    setSuccess('Ledger entry recorded.')
  } catch (apiError) {
    setError(apiError, 'Unable to record account transaction.')
  } finally {
    saving.value = false
  }
}

async function createTransfer() {
  if (!transferForm.from_account_id || !transferForm.to_account_id) {
    error.value = 'Select source and destination accounts.'
    success.value = ''
    return
  }

  if (transferForm.from_account_id === transferForm.to_account_id) {
    error.value = 'Source and destination accounts must be different.'
    success.value = ''
    return
  }

  saving.value = true
  clearMessages()

  try {
    await accountingService.createTransfer({
      from_account_id: Number(transferForm.from_account_id),
      to_account_id: Number(transferForm.to_account_id),
      transaction_date: transferForm.transaction_date,
      amount: Number(transferForm.amount),
      description: transferForm.description,
      reference: transferForm.reference || null,
      notes: transferForm.notes || null,
    })
    transferForm.amount = 0
    transferForm.description = ''
    transferForm.reference = ''
    transferForm.notes = ''
    await load()
    setSuccess('Account transfer recorded.')
  } catch (apiError) {
    setError(apiError, 'Unable to record account transfer.')
  } finally {
    saving.value = false
  }
}

async function createCategory() {
  if (!categoryForm.name.trim()) {
    return
  }

  saving.value = true
  clearMessages()

  try {
    const category = await accountingService.createCategory({ name: categoryForm.name.trim() })
    categories.value = [...categories.value, category].sort((a, b) => a.name.localeCompare(b.name))
    categoryForm.name = ''
    setSuccess('Expense category created.')
  } catch (apiError) {
    setError(apiError, 'Unable to create expense category.')
  } finally {
    saving.value = false
  }
}

function startCategoryEdit(category: ExpenseCategory) {
  editingCategory.value = category
  categoryEditForm.name = category.name
  categoryEditForm.status = category.status
}

function cancelCategoryEdit() {
  editingCategory.value = null
  categoryEditForm.name = ''
  categoryEditForm.status = 'active'
}

async function updateCategory() {
  if (!editingCategory.value || !categoryEditForm.name.trim()) {
    return
  }

  saving.value = true
  clearMessages()

  try {
    await accountingService.updateCategory(editingCategory.value, {
      name: categoryEditForm.name.trim(),
      status: categoryEditForm.status,
    })
    cancelCategoryEdit()
    await load()
    setSuccess('Expense category updated.')
  } catch (apiError) {
    setError(apiError, 'Unable to update expense category.')
  } finally {
    saving.value = false
  }
}

async function deactivateCategory(category: ExpenseCategory) {
  saving.value = true
  clearMessages()

  try {
    await accountingService.updateCategory(category, { status: 'inactive' })
    if (editingCategory.value?.id === category.id) {
      cancelCategoryEdit()
    }
    await load()
    setSuccess('Expense category deactivated.')
  } catch (apiError) {
    setError(apiError, 'Unable to deactivate expense category.')
  } finally {
    saving.value = false
  }
}

function resetExpenseForm() {
  editingExpense.value = null
  expenseForm.expense_category_id = ''
  expenseForm.financial_account_id = ''
  expenseForm.expense_date = today.toISOString().slice(0, 10)
  expenseForm.description = ''
  expenseForm.amount = 0
  expenseForm.payment_method = 'cash'
  expenseForm.vendor = ''
  expenseForm.reference = ''
  expenseForm.notes = ''
  expenseForm.status = 'recorded'
}

function startEdit(expense: Expense) {
  editingExpense.value = expense
  expenseForm.expense_category_id = expense.category?.id ? String(expense.category.id) : ''
  expenseForm.financial_account_id = expense.financial_account?.id ? String(expense.financial_account.id) : ''
  expenseForm.expense_date = expense.expense_date
  expenseForm.description = expense.description
  expenseForm.amount = Number(expense.amount)
  expenseForm.payment_method = expense.payment_method
  expenseForm.vendor = expense.vendor || ''
  expenseForm.reference = expense.reference || ''
  expenseForm.notes = expense.notes || ''
  expenseForm.status = expense.status
}

async function submitExpense() {
  saving.value = true
  clearMessages()

  try {
    const payload = {
      expense_category_id: expenseForm.expense_category_id ? Number(expenseForm.expense_category_id) : null,
      financial_account_id: expenseForm.financial_account_id ? Number(expenseForm.financial_account_id) : null,
      expense_date: expenseForm.expense_date,
      description: expenseForm.description,
      amount: Number(expenseForm.amount),
      payment_method: expenseForm.payment_method,
      vendor: expenseForm.vendor || null,
      reference: expenseForm.reference || null,
      notes: expenseForm.notes || null,
      status: expenseForm.status,
    }

    const wasEditing = Boolean(editingExpense.value)
    if (editingExpense.value) {
      await accountingService.updateExpense(editingExpense.value, payload)
    } else {
      await accountingService.createExpense(payload)
    }

    resetExpenseForm()
    filters.page = 1
    await load()
    setSuccess(wasEditing ? 'Expense updated.' : 'Expense recorded.')
  } catch (apiError) {
    setError(apiError, editingExpense.value ? 'Unable to update expense.' : 'Unable to record expense.')
  } finally {
    saving.value = false
  }
}

async function voidExpense(expense: Expense) {
  saving.value = true
  clearMessages()

  try {
    await accountingService.updateExpense(expense, { status: 'void' })
    await load()
    setSuccess(`${expense.expense_number} voided.`)
  } catch (apiError) {
    setError(apiError, 'Unable to void expense.')
  } finally {
    saving.value = false
  }
}

async function exportExpenses() {
  if (!validateExpenseDateRange()) {
    return
  }

  clearMessages()

  try {
    const blob = await accountingService.exportExpensesCsv(cleanFilters())
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'accounting-expenses.csv'
    link.click()
    window.setTimeout(() => window.URL.revokeObjectURL(url), 60_000)
    setSuccess('Expense export is ready.')
  } catch (apiError) {
    setError(apiError, 'Unable to export expenses.')
  }
}

async function applyFilters() {
  if (!validateExpenseDateRange()) {
    return
  }

  filters.page = 1
  startDate.value = filters.date_from || startDate.value
  endDate.value = filters.date_to || endDate.value
  await load()
}

async function goToPage(page: number) {
  filters.page = Math.min(Math.max(page, 1), meta.value?.last_page || 1)
  await load()
}

async function changeExpensePerPage() {
  filters.page = 1
  await load()
}

onMounted(async () => {
  await companyContext.loadCurrent()
  await load()
})
</script>

<template>
  <section class="stack">
    <article class="panel">
      <div class="topbar" style="margin-bottom: 0">
        <div>
          <h2>Finance</h2>
          <p v-if="summary">{{ summary.period.start_date }} to {{ summary.period.end_date }}</p>
          <p v-if="loading">Loading finance data...</p>
          <p v-if="error" class="error">{{ error }}</p>
          <p v-if="success" class="success">{{ success }}</p>
        </div>
        <form class="inline-actions" @submit.prevent="applyFilters">
          <div class="field">
            <label for="finance_start">Start</label>
            <input id="finance_start" v-model="filters.date_from" type="date" />
          </div>
          <div class="field">
            <label for="finance_end">End</label>
            <input id="finance_end" v-model="filters.date_to" type="date" />
          </div>
          <button class="button primary" type="submit" :disabled="loading || !currentCompanyId">Apply</button>
        </form>
      </div>
    </article>

    <section class="grid compact-grid">
      <article class="metric">
        <span>Total Income</span>
        <strong>BDT {{ money(summary?.income.total) }}</strong>
      </article>
      <article class="metric">
        <span>Expenses</span>
        <strong>BDT {{ money(summary?.expenses.total) }}</strong>
      </article>
      <article class="metric">
        <span>Net Profit</span>
        <strong :class="profitClass">BDT {{ money(summary?.net_profit) }}</strong>
      </article>
      <article class="metric">
        <span>Expense Count</span>
        <strong>{{ summary?.expenses.count || 0 }}</strong>
      </article>
      <article class="metric">
        <span>Account Balance</span>
        <strong>BDT {{ money(totalAccountBalance) }}</strong>
      </article>
    </section>

    <section class="grid wide-grid">
      <article v-if="canManageAccounting" class="panel stack">
        <div class="topbar" style="margin-bottom: 0">
          <h2>{{ formTitle }}</h2>
          <button v-if="editingExpense" class="button ghost" type="button" @click="resetExpenseForm">Cancel</button>
        </div>
        <form class="form" @submit.prevent="submitExpense">
          <div class="field">
            <label for="expense_category">Category</label>
            <select id="expense_category" v-model="expenseForm.expense_category_id">
              <option value="">Uncategorized</option>
              <option v-for="category in categories" :key="category.id" :value="String(category.id)">
                {{ category.name }}
              </option>
            </select>
          </div>
          <div class="field">
            <label for="expense_account">Paid From</label>
            <select id="expense_account" v-model="expenseForm.financial_account_id">
              <option value="">No account ledger</option>
              <option v-for="account in accounts" :key="account.id" :value="String(account.id)">
                {{ account.name }} - BDT {{ account.current_balance }}
              </option>
            </select>
          </div>
          <div class="grid compact-grid">
            <div class="field">
              <label for="expense_date">Date</label>
              <input id="expense_date" v-model="expenseForm.expense_date" type="date" required />
            </div>
            <div class="field">
              <label for="expense_amount">Amount</label>
              <input id="expense_amount" v-model.number="expenseForm.amount" min="0.01" step="0.01" type="number" required />
            </div>
          </div>
          <div class="field">
            <label for="expense_description">Description</label>
            <input id="expense_description" v-model="expenseForm.description" type="text" required />
          </div>
          <div class="grid compact-grid">
            <div class="field">
              <label for="expense_method">Payment</label>
              <select id="expense_method" v-model="expenseForm.payment_method">
                <option value="cash">Cash</option>
                <option value="card">Card</option>
                <option value="bank">Bank</option>
                <option value="mobile_banking">Mobile banking</option>
                <option value="cheque">Cheque</option>
                <option value="other">Other</option>
              </select>
            </div>
            <div class="field">
              <label for="expense_vendor">Vendor</label>
              <input id="expense_vendor" v-model="expenseForm.vendor" type="text" />
            </div>
            <div class="field">
              <label for="expense_status">Status</label>
              <select id="expense_status" v-model="expenseForm.status">
                <option value="recorded">Recorded</option>
                <option value="void">Void</option>
              </select>
            </div>
          </div>
          <div class="field">
            <label for="expense_reference">Reference</label>
            <input id="expense_reference" v-model="expenseForm.reference" type="text" />
          </div>
          <div class="field">
            <label for="expense_notes">Notes</label>
            <textarea id="expense_notes" v-model="expenseForm.notes" rows="3"></textarea>
          </div>
          <button class="button primary" type="submit" :disabled="saving || !currentCompanyId">{{ formButtonLabel }}</button>
        </form>
      </article>

      <article class="panel stack">
        <h2>Categories</h2>
        <form v-if="canManageAccounting" class="inline-actions" @submit.prevent="createCategory">
          <div class="field">
            <label for="category_name">Name</label>
            <input id="category_name" v-model="categoryForm.name" type="text" placeholder="Utilities" />
          </div>
          <button class="button ghost" type="submit" :disabled="saving || !categoryForm.name.trim()">Add</button>
        </form>
        <form v-if="canManageAccounting && editingCategory" class="form" @submit.prevent="updateCategory">
          <div class="topbar" style="margin-bottom: 0">
            <h3>Edit Category</h3>
            <button class="button ghost" type="button" @click="cancelCategoryEdit">Cancel</button>
          </div>
          <div class="field">
            <label for="edit_category_name">Name</label>
            <input id="edit_category_name" v-model="categoryEditForm.name" type="text" />
          </div>
          <div class="field">
            <label for="edit_category_status">Status</label>
            <select id="edit_category_status" v-model="categoryEditForm.status">
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
          <button class="button primary" type="submit" :disabled="saving || !categoryEditForm.name.trim()">Update Category</button>
        </form>
        <div v-for="category in categories" :key="category.id" class="list-item">
          <div>
            <strong>{{ category.name }}</strong>
            <span>{{ category.slug }}</span>
          </div>
          <div class="text-right">
            <strong :class="statusClass(category.status)">{{ category.status }}</strong>
            <div v-if="canManageAccounting" class="inline-actions" style="justify-content: flex-end; margin-top: 8px">
              <button class="button ghost" type="button" @click="startCategoryEdit(category)">Edit</button>
              <button class="button ghost" type="button" :disabled="saving || category.status === 'inactive'" @click="deactivateCategory(category)">Deactivate</button>
            </div>
          </div>
        </div>
        <p v-if="categories.length === 0">No categories yet.</p>
      </article>

      <article class="panel stack">
        <h2>Accounts</h2>
        <form v-if="canManageAccounting" class="form" @submit.prevent="createAccount">
          <div class="field">
            <label for="account_name">Name</label>
            <input id="account_name" v-model="accountForm.name" type="text" placeholder="Main Cash" />
          </div>
          <div class="grid compact-grid">
            <div class="field">
              <label for="account_type">Type</label>
              <select id="account_type" v-model="accountForm.type">
                <option value="cash">Cash</option>
                <option value="bank">Bank</option>
                <option value="mobile_wallet">Mobile wallet</option>
                <option value="card">Card</option>
                <option value="other">Other</option>
              </select>
            </div>
            <div class="field">
              <label for="opening_balance">Opening</label>
              <input id="opening_balance" v-model.number="accountForm.opening_balance" step="0.01" type="number" />
            </div>
          </div>
          <button class="button ghost" type="submit" :disabled="saving || !accountForm.name.trim()">Add Account</button>
        </form>
        <form v-if="canManageAccounting && editingAccount" class="form" @submit.prevent="updateAccount">
          <div class="topbar" style="margin-bottom: 0">
            <h3>Edit Account</h3>
            <button class="button ghost" type="button" @click="cancelAccountEdit">Cancel</button>
          </div>
          <div class="field">
            <label for="edit_account_name">Name</label>
            <input id="edit_account_name" v-model="accountEditForm.name" type="text" />
          </div>
          <div class="grid compact-grid">
            <div class="field">
              <label for="edit_account_type">Type</label>
              <select id="edit_account_type" v-model="accountEditForm.type">
                <option value="cash">Cash</option>
                <option value="bank">Bank</option>
                <option value="mobile_wallet">Mobile wallet</option>
                <option value="card">Card</option>
                <option value="other">Other</option>
              </select>
            </div>
            <div class="field">
              <label for="edit_opening_balance">Opening</label>
              <input id="edit_opening_balance" v-model.number="accountEditForm.opening_balance" step="0.01" type="number" />
            </div>
            <div class="field">
              <label for="edit_account_status">Status</label>
              <select id="edit_account_status" v-model="accountEditForm.status">
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
              </select>
            </div>
          </div>
          <button class="button primary" type="submit" :disabled="saving || !accountEditForm.name.trim()">Update Account</button>
        </form>
        <div v-for="account in accounts" :key="account.id" class="list-item">
          <div>
            <strong>{{ account.name }}</strong>
            <span>{{ account.type }} - opening BDT {{ account.opening_balance }}</span>
          </div>
          <div class="text-right">
            <strong>BDT {{ account.current_balance }}</strong>
            <span :class="statusClass(account.status)">{{ account.status }}</span>
            <div v-if="canManageAccounting" class="inline-actions" style="justify-content: flex-end; margin-top: 8px">
              <button class="button ghost" type="button" @click="startAccountEdit(account)">Edit</button>
              <button class="button ghost" type="button" :disabled="saving || account.status === 'inactive'" @click="deactivateAccount(account)">Deactivate</button>
            </div>
          </div>
        </div>
        <p v-if="accounts.length === 0">No accounts yet.</p>
      </article>

      <article v-if="canManageAccounting" class="panel stack">
        <h2>Expense Breakdown</h2>
        <div v-for="row in summary?.expenses.by_category" :key="row.category" class="list-item">
          <div>
            <strong>{{ row.category }}</strong>
            <span>{{ row.count }} entries</span>
          </div>
          <span>BDT {{ row.total }}</span>
        </div>
        <p v-if="summary?.expenses.by_category.length === 0">No expense data in this period.</p>
        <h3>Income Sources</h3>
        <div class="list-item">
          <div>
            <strong>Invoice Payments</strong>
            <span>Received in selected period</span>
          </div>
          <span>BDT {{ money(summary?.income.invoice_payments) }}</span>
        </div>
        <div class="list-item">
          <div>
            <strong>POS Sales</strong>
            <span>Paid sales in selected period</span>
          </div>
          <span>BDT {{ money(summary?.income.pos_sales) }}</span>
        </div>
      </article>
    </section>

    <section class="grid wide-grid">
      <article v-if="canManageAccounting" class="panel stack">
        <h2>Manual Ledger Entry</h2>
        <form class="form" @submit.prevent="createTransaction">
          <div class="field">
            <label for="transaction_account">Account</label>
            <select id="transaction_account" v-model="transactionForm.financial_account_id" required>
              <option value="">Select account</option>
              <option v-for="account in accounts" :key="account.id" :value="String(account.id)">
                {{ account.name }}
              </option>
            </select>
          </div>
          <div class="grid compact-grid">
            <div class="field">
              <label for="transaction_date">Date</label>
              <input id="transaction_date" v-model="transactionForm.transaction_date" type="date" required />
            </div>
            <div class="field">
              <label for="transaction_amount">Amount</label>
              <input id="transaction_amount" v-model.number="transactionForm.amount" min="0.01" step="0.01" type="number" required />
            </div>
          </div>
          <div class="grid compact-grid">
            <div class="field">
              <label for="transaction_type">Type</label>
              <select id="transaction_type" v-model="transactionForm.type">
                <option value="income">Income</option>
                <option value="expense">Expense</option>
                <option value="adjustment">Adjustment</option>
                <option value="transfer">Transfer</option>
              </select>
            </div>
            <div class="field">
              <label for="transaction_direction">Direction</label>
              <select id="transaction_direction" v-model="transactionForm.direction">
                <option value="inflow">Inflow</option>
                <option value="outflow">Outflow</option>
              </select>
            </div>
          </div>
          <div class="field">
            <label for="transaction_description">Description</label>
            <input id="transaction_description" v-model="transactionForm.description" type="text" required />
          </div>
          <div class="field">
            <label for="transaction_reference">Reference</label>
            <input id="transaction_reference" v-model="transactionForm.reference" type="text" />
          </div>
          <button class="button primary" type="submit" :disabled="saving || accounts.length === 0">Save Entry</button>
        </form>
      </article>

      <article v-if="canManageAccounting" class="panel stack">
        <h2>Account Transfer</h2>
        <form class="form" @submit.prevent="createTransfer">
          <div class="grid compact-grid">
            <div class="field">
              <label for="transfer_from">From</label>
              <select id="transfer_from" v-model="transferForm.from_account_id" required>
                <option value="">Select account</option>
                <option v-for="account in accounts" :key="account.id" :value="String(account.id)">
                  {{ account.name }} - BDT {{ account.current_balance }}
                </option>
              </select>
            </div>
            <div class="field">
              <label for="transfer_to">To</label>
              <select id="transfer_to" v-model="transferForm.to_account_id" required>
                <option value="">Select account</option>
                <option v-for="account in accounts" :key="account.id" :value="String(account.id)">
                  {{ account.name }}
                </option>
              </select>
            </div>
          </div>
          <div class="grid compact-grid">
            <div class="field">
              <label for="transfer_date">Date</label>
              <input id="transfer_date" v-model="transferForm.transaction_date" type="date" required />
            </div>
            <div class="field">
              <label for="transfer_amount">Amount</label>
              <input id="transfer_amount" v-model.number="transferForm.amount" min="0.01" step="0.01" type="number" required />
            </div>
          </div>
          <div class="field">
            <label for="transfer_description">Description</label>
            <input id="transfer_description" v-model="transferForm.description" type="text" placeholder="Cash deposit" required />
          </div>
          <div class="field">
            <label for="transfer_reference">Reference</label>
            <input id="transfer_reference" v-model="transferForm.reference" type="text" />
          </div>
          <button class="button primary" type="submit" :disabled="saving || accounts.length < 2">Transfer</button>
        </form>
      </article>

      <article class="panel stack">
        <div class="topbar" style="margin-bottom: 0">
          <div>
            <h2>Ledger</h2>
            <p v-if="transactionMeta">{{ transactionMeta.total }} records</p>
          </div>
          <form class="inline-actions" @submit.prevent="applyTransactionFilters">
            <div class="field">
              <label for="ledger_account">Account</label>
              <select id="ledger_account" v-model="transactionFilters.financial_account_id">
                <option value="">All</option>
                <option v-for="account in accounts" :key="account.id" :value="String(account.id)">
                  {{ account.name }}
                </option>
              </select>
            </div>
            <div class="field">
              <label for="ledger_type">Type</label>
              <select id="ledger_type" v-model="transactionFilters.type">
                <option value="">All</option>
                <option value="income">Income</option>
                <option value="expense">Expense</option>
                <option value="adjustment">Adjustment</option>
                <option value="transfer">Transfer</option>
              </select>
            </div>
            <div class="field">
              <label for="ledger_direction">Direction</label>
              <select id="ledger_direction" v-model="transactionFilters.direction">
                <option value="">All</option>
                <option value="inflow">Inflow</option>
                <option value="outflow">Outflow</option>
              </select>
            </div>
            <div class="field">
              <label for="ledger_from">From</label>
              <input id="ledger_from" v-model="transactionFilters.date_from" type="date" />
            </div>
            <div class="field">
              <label for="ledger_to">To</label>
              <input id="ledger_to" v-model="transactionFilters.date_to" type="date" />
            </div>
            <button class="button ghost" type="submit" :disabled="loading">Filter</button>
            <button class="button ghost" type="button" :disabled="loading" @click="exportTransactions">Export CSV</button>
          </form>
        </div>
        <div v-for="transaction in transactions" :key="transaction.id" class="list-item">
          <div>
            <strong>{{ transaction.description }}</strong>
            <span>{{ transaction.transaction_date }} - {{ transaction.financial_account?.name || 'Account' }}</span>
            <span>{{ transaction.type }}</span>
          </div>
          <div class="inline-actions">
            <span :class="directionClass(transaction.direction)">{{ transaction.direction }}</span>
            <strong>{{ transaction.direction === 'inflow' ? '+' : '-' }} BDT {{ transaction.amount }}</strong>
          </div>
        </div>
        <p v-if="transactions.length === 0">No ledger transactions yet.</p>
        <div v-if="transactionMeta" class="inline-actions">
          <span>
            Showing {{ transactionMeta.from || 0 }}-{{ transactionMeta.to || 0 }} of {{ transactionMeta.total }}
          </span>
          <label class="inline-actions">
            <span>Per page</span>
            <select v-model.number="transactionFilters.per_page" :disabled="loading" @change="changeTransactionPerPage">
              <option :value="8">8</option>
              <option :value="25">25</option>
              <option :value="50">50</option>
            </select>
          </label>
          <button
            class="button ghost"
            type="button"
            :disabled="transactionMeta.current_page <= 1 || loading"
            @click="goToTransactionPage(transactionMeta.current_page - 1)"
          >
            Previous
          </button>
          <span>Page {{ transactionMeta.current_page }} of {{ transactionMeta.last_page }}</span>
          <button
            class="button ghost"
            type="button"
            :disabled="transactionMeta.current_page >= transactionMeta.last_page || loading"
            @click="goToTransactionPage(transactionMeta.current_page + 1)"
          >
            Next
          </button>
        </div>
      </article>
    </section>

    <article class="panel stack">
      <div class="topbar" style="margin-bottom: 0">
        <div>
          <h2>Expenses</h2>
          <p v-if="meta">{{ meta.total }} records</p>
        </div>
        <form class="inline-actions" @submit.prevent="applyFilters">
          <div class="field">
            <label for="expense_search">Search</label>
            <input id="expense_search" v-model="filters.search" type="search" placeholder="Description, vendor, ref" />
          </div>
          <div class="field">
            <label for="filter_category">Category</label>
            <select id="filter_category" v-model="filters.expense_category_id">
              <option value="">All</option>
              <option v-for="category in categories" :key="category.id" :value="String(category.id)">
                {{ category.name }}
              </option>
            </select>
          </div>
          <div class="field">
            <label for="filter_account">Account</label>
            <select id="filter_account" v-model="filters.financial_account_id">
              <option value="">All</option>
              <option v-for="account in accounts" :key="account.id" :value="String(account.id)">
                {{ account.name }}
              </option>
            </select>
          </div>
          <div class="field">
            <label for="filter_method">Payment</label>
            <select id="filter_method" v-model="filters.payment_method">
              <option value="">All</option>
              <option value="cash">Cash</option>
              <option value="card">Card</option>
              <option value="bank">Bank</option>
              <option value="mobile_banking">Mobile banking</option>
              <option value="cheque">Cheque</option>
              <option value="other">Other</option>
            </select>
          </div>
          <button class="button ghost" type="submit" :disabled="loading">Filter</button>
          <button class="button ghost" type="button" :disabled="loading" @click="exportExpenses">Export CSV</button>
        </form>
      </div>

      <div v-for="expense in expenses" :key="expense.id" class="list-item">
        <div>
          <strong>{{ expense.description }}</strong>
          <span>
            {{ expense.expense_number }} - {{ expense.expense_date }} - {{ expense.category?.name || 'Uncategorized' }}
          </span>
          <span v-if="expense.financial_account">{{ expense.financial_account.name }}</span>
          <span v-if="expense.vendor">{{ expense.vendor }}</span>
        </div>
        <div class="text-right">
          <strong>BDT {{ expense.amount }}</strong>
          <span>{{ expense.payment_method }}</span>
          <span :class="statusClass(expense.status)">{{ expense.status }}</span>
          <div v-if="canManageAccounting" class="inline-actions" style="justify-content: flex-end; margin-top: 8px">
            <button class="button ghost" type="button" @click="startEdit(expense)">Edit</button>
            <button v-if="expense.status !== 'void'" class="button ghost" type="button" :disabled="saving" @click="voidExpense(expense)">
              Void
            </button>
          </div>
        </div>
      </div>
      <p v-if="expenses.length === 0">No expenses found.</p>

      <div v-if="meta" class="inline-actions">
        <span>
          Showing {{ meta.from || 0 }}-{{ meta.to || 0 }} of {{ meta.total }}
        </span>
        <label class="inline-actions">
          <span>Per page</span>
          <select v-model.number="filters.per_page" :disabled="loading" @change="changeExpensePerPage">
            <option :value="10">10</option>
            <option :value="25">25</option>
            <option :value="50">50</option>
          </select>
        </label>
        <button class="button ghost" type="button" :disabled="meta.current_page <= 1 || loading" @click="goToPage(meta.current_page - 1)">
          Previous
        </button>
        <span>Page {{ meta.current_page }} of {{ meta.last_page }}</span>
        <button class="button ghost" type="button" :disabled="meta.current_page >= meta.last_page || loading" @click="goToPage(meta.current_page + 1)">
          Next
        </button>
      </div>
    </article>
  </section>
</template>
