<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from 'vue'
import { getApiErrorMessage } from '@/services/api'
import { accountingService, type FinancialAccount } from '@/modules/accounting/services/accountingService'
import { invoiceService, type Customer, type Invoice, type PaginationMeta } from '@/modules/invoice/services/invoiceService'
import { useCompanyContextStore } from '@/stores/companyContext'

interface InvoiceFormItem {
  description: string
  quantity: number
  unit_price: number
  tax_rate: number
  discount_amount: number
}

interface CustomerPortalForm {
  name: string
  email: string
  password: string
  status: 'active' | 'inactive'
  exists: boolean
  loaded: boolean
  saving: boolean
  error: string
  message: string
}

const customers = ref<Customer[]>([])
const accounts = ref<FinancialAccount[]>([])
const invoices = ref<Invoice[]>([])
const selectedInvoice = ref<Invoice | null>(null)
const companyContext = useCompanyContextStore()
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const success = ref('')
const currentCompanyId = ref(localStorage.getItem('current_company_id') || '')
const paymentAccountId = ref('')
const editingCustomer = ref<Customer | null>(null)
const customerForm = ref({
  name: '',
  email: '',
  phone: '',
})
const customerEditForm = ref({
  name: '',
  email: '',
  phone: '',
  address: '',
  status: 'active',
})
const portalAccountForms = ref<Record<number, CustomerPortalForm>>({})
const filters = ref({
  search: '',
  status: '',
  date_from: '',
  date_to: '',
})
const invoicePagination = ref<PaginationMeta>({
  current_page: 1,
  from: null,
  last_page: 1,
  per_page: 10,
  to: null,
  total: 0,
})
const invoiceForm = ref({
  customer_id: '',
  issue_date: new Date().toISOString().slice(0, 10),
  due_date: '',
})
const invoiceItems = ref<InvoiceFormItem[]>([
  {
    description: '',
    quantity: 1,
    unit_price: 0,
    tax_rate: 0,
    discount_amount: 0,
  },
])

const invoiceTotalPreview = computed(() => {
  return invoiceItems.value.reduce((total, item) => total + lineTotal(item), 0).toFixed(2)
})
const canManageInvoice = computed(() => companyContext.hasPermission('invoice.manage'))
const visibleInvoiceTotal = computed(() => invoices.value.reduce((total, invoice) => total + Number(invoice.total || 0), 0))
const visibleDueTotal = computed(() => invoices.value.reduce((total, invoice) => total + Number(invoice.due_total || 0), 0))
const visibleOverdueCount = computed(() => {
  const today = new Date().toISOString().slice(0, 10)

  return invoices.value.filter((invoice) => {
    return invoice.due_date && invoice.due_date < today && Number(invoice.due_total) > 0 && invoice.status !== 'cancelled'
  }).length
})

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

  loading.value = true
  error.value = ''

  try {
    const canUseAccounting = companyContext.hasFeature('accounting')
    const [customerData, invoicePage, accountData] = await Promise.all([
      invoiceService.customers(),
      invoiceService.paginatedInvoices({
        search: filters.value.search || undefined,
        status: filters.value.status || undefined,
        date_from: filters.value.date_from || undefined,
        date_to: filters.value.date_to || undefined,
        page: invoicePagination.value.current_page,
        per_page: invoicePagination.value.per_page,
      }),
      canUseAccounting ? accountingService.accounts() : Promise.resolve([]),
    ])
    customers.value = customerData
    initializePortalForms(customerData)
    invoices.value = invoicePage.data
    invoicePagination.value = invoicePage.meta
    accounts.value = accountData
  } catch (loadError) {
    error.value = getApiErrorMessage(loadError, 'Unable to load invoice data.')
  } finally {
    loading.value = false
  }
}

async function loadInvoicePage(page: number) {
  invoicePagination.value.current_page = Math.min(Math.max(page, 1), invoicePagination.value.last_page || 1)
  await load()
}

async function applyFilters() {
  if (filters.value.date_from && filters.value.date_to && filters.value.date_from > filters.value.date_to) {
    error.value = 'From date must be before To date.'
    return
  }

  invoicePagination.value.current_page = 1
  await load()
}

async function resetFilters() {
  filters.value = {
    search: '',
    status: '',
    date_from: '',
    date_to: '',
  }
  invoicePagination.value.current_page = 1
  await load()
}

async function createCustomer() {
  if (!customerForm.value.name.trim()) {
    return
  }

  saving.value = true
  error.value = ''
  success.value = ''

  try {
    const customer = await invoiceService.createCustomer({
      name: customerForm.value.name.trim(),
      email: customerForm.value.email || undefined,
      phone: customerForm.value.phone || undefined,
    })
    customers.value = [...customers.value, customer]
    ensurePortalForm(customer)
    customerForm.value = {
      name: '',
      email: '',
      phone: '',
    }
    success.value = 'Customer created.'
  } catch (createCustomerError) {
    error.value = getApiErrorMessage(createCustomerError, 'Unable to create customer.')
  } finally {
    saving.value = false
  }
}

function initializePortalForms(customerData: Customer[]) {
  customerData.forEach((customer) => ensurePortalForm(customer))
}

function ensurePortalForm(customer: Customer): CustomerPortalForm {
  if (!portalAccountForms.value[customer.id]) {
    portalAccountForms.value[customer.id] = portalFormFromCustomer(customer)
  } else if (!portalAccountForms.value[customer.id].saving) {
    const existing = portalAccountForms.value[customer.id]
    const synced = portalFormFromCustomer(customer)

    existing.name = synced.name
    existing.email = synced.email
    existing.status = synced.status
    existing.exists = synced.exists
    existing.loaded = synced.loaded
  }

  return portalAccountForms.value[customer.id]
}

function portalFormFromCustomer(customer: Customer): CustomerPortalForm {
  return {
    name: customer.portal_account?.name || customer.name,
    email: customer.portal_account?.email || customer.email || '',
    password: '',
    status: customer.portal_account?.status === 'inactive' ? 'inactive' : 'active',
    exists: Boolean(customer.portal_account),
    loaded: Boolean(customer.portal_account),
    saving: false,
    error: '',
    message: '',
  }
}

async function loadCustomerPortalAccount(customer: Customer) {
  const form = ensurePortalForm(customer)
  form.saving = true
  form.error = ''
  form.message = ''

  try {
    const account = await invoiceService.customerPortalAccount(customer)
    form.name = account.name
    form.email = account.email
    form.password = ''
    form.status = account.status === 'inactive' ? 'inactive' : 'active'
    form.exists = true
    form.loaded = true
    form.message = 'Portal account loaded.'
    customers.value = customers.value.map((item) => item.id === customer.id
      ? { ...item, portal_account: {
        id: account.id,
        name: account.name,
        email: account.email,
        status: account.status,
        last_login_at: account.last_login_at,
      } }
      : item)
  } catch (loadPortalError) {
    form.name = customer.name
    form.email = customer.email || ''
    form.password = ''
    form.status = 'active'
    form.exists = false
    form.loaded = true
    form.message = getApiErrorMessage(loadPortalError, 'No portal account yet.')
    customers.value = customers.value.map((item) => item.id === customer.id
      ? { ...item, portal_account: null }
      : item)
  } finally {
    form.saving = false
  }
}

async function saveCustomerPortalAccount(customer: Customer) {
  const form = ensurePortalForm(customer)

  if (!form.email.trim()) {
    form.error = 'Portal email is required.'
    return
  }

  if (!form.exists && !form.password.trim()) {
    form.error = 'Password is required for a new portal account.'
    return
  }

  form.saving = true
  form.error = ''
  form.message = ''

  try {
    const account = await invoiceService.saveCustomerPortalAccount(customer, {
      name: form.name.trim() || customer.name,
      email: form.email.trim(),
      password: form.password.trim() || undefined,
      status: form.status,
    })
    form.name = account.name
    form.email = account.email
    form.password = ''
    form.status = account.status === 'inactive' ? 'inactive' : 'active'
    form.exists = true
    form.loaded = true
    form.message = 'Portal account saved.'
    customers.value = customers.value.map((item) => item.id === customer.id
      ? { ...item, portal_account: {
        id: account.id,
        name: account.name,
        email: account.email,
        status: account.status,
        last_login_at: account.last_login_at,
      } }
      : item)
  } catch (savePortalError) {
    form.error = getApiErrorMessage(savePortalError, 'Unable to save portal account.')
  } finally {
    form.saving = false
  }
}

async function revokeCustomerPortalSessions(customer: Customer) {
  const form = ensurePortalForm(customer)

  if (!form.exists) {
    form.error = 'Portal account must be saved first.'
    return
  }

  form.saving = true
  form.error = ''
  form.message = ''

  try {
    await invoiceService.revokeCustomerPortalSessions(customer)
    form.message = 'Customer portal sessions logged out.'
  } catch (revokePortalError) {
    form.error = getApiErrorMessage(revokePortalError, 'Unable to revoke portal sessions.')
  } finally {
    form.saving = false
  }
}

function startCustomerEdit(customer: Customer) {
  editingCustomer.value = customer
  customerEditForm.value = {
    name: customer.name,
    email: customer.email || '',
    phone: customer.phone || '',
    address: customer.address || '',
    status: customer.status,
  }
}

function cancelCustomerEdit() {
  editingCustomer.value = null
  customerEditForm.value = {
    name: '',
    email: '',
    phone: '',
    address: '',
    status: 'active',
  }
}

async function updateCustomer() {
  if (!editingCustomer.value || !customerEditForm.value.name.trim()) {
    return
  }

  saving.value = true
  error.value = ''
  success.value = ''

  try {
    await invoiceService.updateCustomer(editingCustomer.value, {
      name: customerEditForm.value.name.trim(),
      email: customerEditForm.value.email || null,
      phone: customerEditForm.value.phone || null,
      address: customerEditForm.value.address || null,
      status: customerEditForm.value.status,
    })
    cancelCustomerEdit()
    await load()
    success.value = 'Customer updated.'
  } catch (updateCustomerError) {
    error.value = getApiErrorMessage(updateCustomerError, 'Unable to update customer.')
  } finally {
    saving.value = false
  }
}

async function deactivateCustomer(customer: Customer) {
  saving.value = true
  error.value = ''
  success.value = ''

  try {
    await invoiceService.updateCustomer(customer, { status: 'inactive' })
    if (editingCustomer.value?.id === customer.id) {
      cancelCustomerEdit()
    }
    await load()
    success.value = 'Customer deactivated.'
  } catch (deactivateCustomerError) {
    error.value = getApiErrorMessage(deactivateCustomerError, 'Unable to deactivate customer.')
  } finally {
    saving.value = false
  }
}

async function createInvoice() {
  if (invoiceForm.value.due_date && invoiceForm.value.due_date < invoiceForm.value.issue_date) {
    error.value = 'Due date cannot be before issue date.'
    return
  }

  saving.value = true
  error.value = ''
  success.value = ''

  try {
    const invoice = await invoiceService.createInvoice({
      customer_id: invoiceForm.value.customer_id ? Number(invoiceForm.value.customer_id) : undefined,
      issue_date: invoiceForm.value.issue_date,
      due_date: invoiceForm.value.due_date || undefined,
      status: 'sent',
      items: invoiceItems.value.map((item) => ({
        description: item.description,
        quantity: Number(item.quantity),
        unit_price: Number(item.unit_price),
        tax_rate: Number(item.tax_rate),
        discount_amount: Number(item.discount_amount),
      })),
    })
    invoices.value = [invoice, ...invoices.value]
    selectedInvoice.value = invoice
    invoicePagination.value.current_page = 1
    await load()
    invoiceItems.value = [{
      description: '',
      quantity: 1,
      unit_price: 0,
      tax_rate: 0,
      discount_amount: 0,
    }]
    success.value = `${invoice.invoice_number} created.`
  } catch (createInvoiceError) {
    error.value = getApiErrorMessage(createInvoiceError, 'Unable to create invoice.')
  } finally {
    saving.value = false
  }
}

async function recordPayment(invoice: Invoice) {
  const amount = Number(invoice.due_total)

  if (amount <= 0) {
    return
  }

  saving.value = true
  error.value = ''
  success.value = ''

  try {
    const updatedInvoice = await invoiceService.recordPayment(
      invoice,
      amount,
      paymentAccountId.value ? Number(paymentAccountId.value) : undefined,
    )
    invoices.value = invoices.value.map((item) => item.id === updatedInvoice.id ? updatedInvoice : item)
    selectedInvoice.value = updatedInvoice
    success.value = `${updatedInvoice.invoice_number} marked paid.`
  } catch (paymentError) {
    error.value = getApiErrorMessage(paymentError, 'Unable to record payment.')
  } finally {
    saving.value = false
  }
}

async function cancelInvoice(invoice: Invoice) {
  saving.value = true
  error.value = ''
  success.value = ''

  try {
    const updatedInvoice = await invoiceService.updateInvoice(invoice, { status: 'cancelled' })
    invoices.value = invoices.value.map((item) => item.id === updatedInvoice.id ? updatedInvoice : item)
    if (selectedInvoice.value?.id === updatedInvoice.id) {
      selectedInvoice.value = updatedInvoice
    }
    success.value = `${updatedInvoice.invoice_number} cancelled.`
  } catch (cancelInvoiceError) {
    error.value = getApiErrorMessage(cancelInvoiceError, 'Unable to cancel invoice.')
  } finally {
    saving.value = false
  }
}

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

function statusLabel(status: string) {
  return status.charAt(0).toUpperCase() + status.slice(1).replace('_', ' ')
}

function statusClass(status: string) {
  return {
    off: ['cancelled', 'draft'].includes(status),
    warn: ['sent', 'partial'].includes(status),
  }
}

function lineTotal(item: InvoiceFormItem) {
  const subtotal = Number(item.quantity || 0) * Number(item.unit_price || 0)
  const taxable = Math.max(subtotal - Number(item.discount_amount || 0), 0)
  const tax = taxable * (Number(item.tax_rate || 0) / 100)

  return taxable + tax
}

function addInvoiceItem() {
  invoiceItems.value.push({
    description: '',
    quantity: 1,
    unit_price: 0,
    tax_rate: 0,
    discount_amount: 0,
  })
}

function removeInvoiceItem(index: number) {
  if (invoiceItems.value.length === 1) {
    return
  }

  invoiceItems.value.splice(index, 1)
}

async function openInvoice(invoice: Invoice) {
  error.value = ''

  try {
    selectedInvoice.value = await invoiceService.invoice(invoice)
  } catch (openInvoiceError) {
    error.value = getApiErrorMessage(openInvoiceError, 'Unable to load invoice preview.')
  }
}

async function printInvoice(invoice: Invoice) {
  await openInvoice(invoice)
  await nextTick()
  window.print()
}

async function exportInvoice(invoice: Invoice) {
  error.value = ''

  try {
    const html = await invoiceService.exportInvoiceHtml(invoice)
    const url = URL.createObjectURL(html)
    window.open(url, '_blank', 'noopener,noreferrer')
    window.setTimeout(() => URL.revokeObjectURL(url), 60_000)
  } catch (exportInvoiceError) {
    error.value = getApiErrorMessage(exportInvoiceError, 'Unable to export invoice.')
  }
}

async function printSelectedInvoice() {
  await nextTick()
  window.print()
}

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

<template>
  <section class="stack">
    <article class="panel no-print">
      <h2>Invoices</h2>
      <p v-if="loading">Loading invoices...</p>
      <p v-if="error" class="error">{{ error }}</p>
      <p v-if="success" class="success">{{ success }}</p>
    </article>

    <section class="grid compact-grid no-print">
      <article class="metric">
        <span>Visible Invoices</span>
        <strong>{{ invoices.length }}</strong>
        <small>{{ invoicePagination.total }} total matching filters</small>
      </article>
      <article class="metric">
        <span>Visible Total</span>
        <strong>BDT {{ money(visibleInvoiceTotal) }}</strong>
        <small>Current page total</small>
      </article>
      <article class="metric">
        <span>Visible Due</span>
        <strong>BDT {{ money(visibleDueTotal) }}</strong>
        <small>{{ visibleOverdueCount }} overdue on this page</small>
      </article>
    </section>

    <section v-if="canManageInvoice" class="grid wide-grid no-print">
      <article class="panel">
        <h2>Create Customer</h2>
        <form class="form" @submit.prevent="createCustomer">
          <div class="field">
            <label for="customer_name">Name</label>
            <input id="customer_name" v-model="customerForm.name" type="text" required />
          </div>
          <div class="field">
            <label for="customer_email">Email</label>
            <input id="customer_email" v-model="customerForm.email" type="email" />
          </div>
          <div class="field">
            <label for="customer_phone">Phone</label>
            <input id="customer_phone" v-model="customerForm.phone" type="text" />
          </div>
          <button class="button primary" type="submit" :disabled="saving || !currentCompanyId">
            {{ saving ? 'Saving...' : 'Add Customer' }}
          </button>
        </form>
        <form v-if="editingCustomer" class="form" @submit.prevent="updateCustomer">
          <div class="field">
            <label for="edit_customer_name">Name</label>
            <input id="edit_customer_name" v-model="customerEditForm.name" type="text" required />
          </div>
          <div class="grid compact-grid">
            <div class="field">
              <label for="edit_customer_email">Email</label>
              <input id="edit_customer_email" v-model="customerEditForm.email" type="email" />
            </div>
            <div class="field">
              <label for="edit_customer_phone">Phone</label>
              <input id="edit_customer_phone" v-model="customerEditForm.phone" type="text" />
            </div>
          </div>
          <div class="field">
            <label for="edit_customer_address">Address</label>
            <textarea id="edit_customer_address" v-model="customerEditForm.address" rows="2"></textarea>
          </div>
          <div class="field">
            <label for="edit_customer_status">Status</label>
            <select id="edit_customer_status" v-model="customerEditForm.status">
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
          <div class="inline-actions">
            <button class="button primary" type="submit" :disabled="saving || !customerEditForm.name.trim()">Save Customer</button>
            <button class="button ghost" type="button" @click="cancelCustomerEdit">Cancel</button>
          </div>
        </form>
        <div v-for="customer in customers" :key="customer.id" class="customer-access-item">
          <div class="list-item">
            <div>
              <strong>{{ customer.name }}</strong>
              <span>{{ customer.email || 'No email' }} - {{ customer.phone || 'No phone' }}</span>
            </div>
            <div class="inline-actions">
              <button class="button ghost" type="button" @click="startCustomerEdit(customer)">Edit</button>
              <button v-if="customer.status !== 'inactive'" class="button ghost" type="button" :disabled="saving" @click="deactivateCustomer(customer)">Deactivate</button>
            </div>
          </div>

          <form v-if="portalAccountForms[customer.id]" class="form portal-account-form" @submit.prevent="saveCustomerPortalAccount(customer)">
            <div class="portal-account-title">
              <strong>Portal Access</strong>
              <span>{{ portalAccountForms[customer.id].exists ? 'Enabled' : 'Not enabled' }}</span>
            </div>
            <div class="grid compact-grid">
              <div class="field">
                <label :for="`portal_name_${customer.id}`">Name</label>
                <input :id="`portal_name_${customer.id}`" v-model="portalAccountForms[customer.id].name" type="text" />
              </div>
              <div class="field">
                <label :for="`portal_email_${customer.id}`">Login Email</label>
                <input :id="`portal_email_${customer.id}`" v-model="portalAccountForms[customer.id].email" type="email" required />
              </div>
              <div class="field">
                <label :for="`portal_password_${customer.id}`">Password</label>
                <input :id="`portal_password_${customer.id}`" v-model="portalAccountForms[customer.id].password" type="password" autocomplete="new-password" />
              </div>
              <div class="field">
                <label :for="`portal_status_${customer.id}`">Status</label>
                <select :id="`portal_status_${customer.id}`" v-model="portalAccountForms[customer.id].status">
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                </select>
              </div>
            </div>
            <p v-if="portalAccountForms[customer.id].error" class="error">{{ portalAccountForms[customer.id].error }}</p>
            <p v-if="portalAccountForms[customer.id].message" class="muted">{{ portalAccountForms[customer.id].message }}</p>
            <div class="inline-actions">
              <button class="button primary" type="submit" :disabled="portalAccountForms[customer.id].saving">
                Save Portal Access
              </button>
              <button class="button ghost" type="button" :disabled="portalAccountForms[customer.id].saving" @click="loadCustomerPortalAccount(customer)">
                Load Existing
              </button>
              <button
                class="button ghost"
                type="button"
                :disabled="portalAccountForms[customer.id].saving || !portalAccountForms[customer.id].exists"
                @click="revokeCustomerPortalSessions(customer)"
              >
                Logout Sessions
              </button>
            </div>
          </form>
        </div>
        <p v-if="customers.length === 0">No customers yet.</p>
      </article>

      <article class="panel">
        <h2>Create Invoice</h2>
        <form class="form" @submit.prevent="createInvoice">
          <div class="field">
            <label for="invoice_customer">Customer</label>
            <select id="invoice_customer" v-model="invoiceForm.customer_id">
              <option value="">Walk-in customer</option>
              <option v-for="customer in customers" :key="customer.id" :value="customer.id">
                {{ customer.name }}
              </option>
            </select>
          </div>
          <div class="field">
            <label for="issue_date">Issue Date</label>
            <input id="issue_date" v-model="invoiceForm.issue_date" type="date" required />
          </div>
          <div class="field">
            <label for="due_date">Due Date</label>
            <input id="due_date" v-model="invoiceForm.due_date" type="date" />
          </div>
          <div class="stack">
            <div v-for="(item, index) in invoiceItems" :key="index" class="panel">
              <div class="field">
                <label :for="`description_${index}`">Item</label>
                <input :id="`description_${index}`" v-model="item.description" type="text" required />
              </div>
              <div class="grid compact-grid">
                <div class="field">
                  <label :for="`quantity_${index}`">Qty</label>
                  <input :id="`quantity_${index}`" v-model.number="item.quantity" min="0.01" step="0.01" type="number" required />
                </div>
                <div class="field">
                  <label :for="`unit_price_${index}`">Price</label>
                  <input :id="`unit_price_${index}`" v-model.number="item.unit_price" min="0" step="0.01" type="number" required />
                </div>
                <div class="field">
                  <label :for="`tax_rate_${index}`">Tax %</label>
                  <input :id="`tax_rate_${index}`" v-model.number="item.tax_rate" min="0" step="0.01" type="number" />
                </div>
                <div class="field">
                  <label :for="`discount_${index}`">Discount</label>
                  <input :id="`discount_${index}`" v-model.number="item.discount_amount" min="0" step="0.01" type="number" />
                </div>
              </div>
              <div class="inline-actions">
                <span>Line total BDT {{ money(lineTotal(item)) }}</span>
                <button class="button ghost" type="button" :disabled="invoiceItems.length === 1" @click="removeInvoiceItem(index)">Remove</button>
              </div>
            </div>
          </div>
          <p>Total preview: BDT {{ invoiceTotalPreview }}</p>
          <button class="button ghost" type="button" @click="addInvoiceItem">Add Item</button>
          <button class="button primary" type="submit" :disabled="saving || !currentCompanyId">
            {{ saving ? 'Saving...' : 'Create Invoice' }}
          </button>
        </form>
      </article>
    </section>

    <article class="panel no-print">
      <h2>Invoice List</h2>
      <form class="form" @submit.prevent="applyFilters">
        <div class="grid compact-grid">
          <div class="field">
            <label for="invoice_search">Search</label>
            <input id="invoice_search" v-model="filters.search" type="search" placeholder="Number or customer" />
          </div>
          <div class="field">
            <label for="invoice_status">Status</label>
            <select id="invoice_status" v-model="filters.status">
              <option value="">All</option>
              <option value="draft">Draft</option>
              <option value="sent">Sent</option>
              <option value="partial">Partial</option>
              <option value="paid">Paid</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </div>
          <div class="field">
            <label for="invoice_date_from">From</label>
            <input id="invoice_date_from" v-model="filters.date_from" type="date" />
          </div>
          <div class="field">
            <label for="invoice_date_to">To</label>
            <input id="invoice_date_to" v-model="filters.date_to" type="date" />
          </div>
          <div class="field">
            <label for="invoice_per_page">Per Page</label>
            <select id="invoice_per_page" v-model.number="invoicePagination.per_page">
              <option :value="10">10</option>
              <option :value="25">25</option>
              <option :value="50">50</option>
            </select>
          </div>
        </div>
        <div class="inline-actions">
          <button class="button primary" type="submit">Apply Filters</button>
          <button class="button ghost" type="button" @click="resetFilters">Reset</button>
        </div>
      </form>
      <div v-if="canManageInvoice && accounts.length > 0" class="inline-actions" style="margin-top: 12px">
        <div class="field">
          <label for="invoice_payment_account">Payment Account</label>
          <select id="invoice_payment_account" v-model="paymentAccountId">
            <option value="">No ledger 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>
      <div class="stack">
        <div v-for="invoice in invoices" :key="invoice.id" class="list-item">
          <div>
            <strong>{{ invoice.invoice_number }}</strong>
            <span>{{ invoice.customer?.name || 'Walk-in customer' }} - Due {{ invoice.due_date || 'N/A' }}</span>
          </div>
          <div class="inline-actions">
            <span class="status-pill" :class="statusClass(invoice.status)">{{ statusLabel(invoice.status) }}</span>
            <span>BDT {{ invoice.due_total }} due</span>
            <button v-if="canManageInvoice && Number(invoice.due_total) > 0" class="button ghost" type="button" :disabled="saving" @click="recordPayment(invoice)">
              Mark paid
            </button>
            <button
              v-if="canManageInvoice && Number(invoice.paid_total) <= 0 && invoice.status !== 'cancelled'"
              class="button ghost"
              type="button"
              :disabled="saving"
              @click="cancelInvoice(invoice)"
            >
              Cancel
            </button>
            <button class="button ghost" type="button" @click="openInvoice(invoice)">Preview</button>
            <button class="button ghost" type="button" @click="exportInvoice(invoice)">Export</button>
            <button class="button primary" type="button" @click="printInvoice(invoice)">Print</button>
          </div>
        </div>
        <p v-if="invoices.length === 0 && !loading">No invoices yet.</p>
      </div>
      <div class="inline-actions">
        <span>
          Showing {{ invoicePagination.from || 0 }}-{{ invoicePagination.to || 0 }} of {{ invoicePagination.total }}
        </span>
        <button
          class="button ghost"
          type="button"
          :disabled="loading || invoicePagination.current_page <= 1"
          @click="loadInvoicePage(invoicePagination.current_page - 1)"
        >
          Previous
        </button>
        <span>Page {{ invoicePagination.current_page }} of {{ invoicePagination.last_page }}</span>
        <button
          class="button ghost"
          type="button"
          :disabled="loading || invoicePagination.current_page >= invoicePagination.last_page"
          @click="loadInvoicePage(invoicePagination.current_page + 1)"
        >
          Next
        </button>
      </div>
    </article>

    <article v-if="selectedInvoice" class="panel print-document">
      <div class="print-header">
        <div>
          <h2>{{ companyContext.company?.name || 'BizNovia' }}</h2>
          <p>{{ companyContext.company?.address || 'Business address' }}</p>
          <p>{{ companyContext.company?.email || '' }} {{ companyContext.company?.phone || '' }}</p>
        </div>
        <div class="print-meta">
          <strong>Invoice</strong>
          <span>{{ selectedInvoice.invoice_number }}</span>
          <span class="status-pill" :class="statusClass(selectedInvoice.status)">{{ statusLabel(selectedInvoice.status) }}</span>
        </div>
      </div>

      <section class="print-grid">
        <div>
          <strong>Bill To</strong>
          <p>{{ selectedInvoice.customer?.name || 'Walk-in customer' }}</p>
          <p>{{ selectedInvoice.customer?.email || '' }}</p>
          <p>{{ selectedInvoice.customer?.phone || '' }}</p>
        </div>
        <div>
          <strong>Dates</strong>
          <p>Issue: {{ selectedInvoice.issue_date }}</p>
          <p>Due: {{ selectedInvoice.due_date || 'N/A' }}</p>
        </div>
      </section>

      <table class="print-table">
        <thead>
          <tr>
            <th>Item</th>
            <th>Qty</th>
            <th>Price</th>
            <th>Tax</th>
            <th>Discount</th>
            <th>Total</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in selectedInvoice.items" :key="item.id || item.description">
            <td>{{ item.description }}</td>
            <td>{{ item.quantity }}</td>
            <td>BDT {{ money(item.unit_price) }}</td>
            <td>BDT {{ money(item.tax_amount) }}</td>
            <td>BDT {{ money(item.discount_amount) }}</td>
            <td>BDT {{ money(item.line_total) }}</td>
          </tr>
        </tbody>
      </table>

      <section class="print-totals">
        <div><span>Subtotal</span><strong>BDT {{ selectedInvoice.subtotal }}</strong></div>
        <div><span>Tax</span><strong>BDT {{ selectedInvoice.tax_total }}</strong></div>
        <div><span>Discount</span><strong>BDT {{ selectedInvoice.discount_total }}</strong></div>
        <div><span>Total</span><strong>BDT {{ selectedInvoice.total }}</strong></div>
        <div><span>Paid</span><strong>BDT {{ selectedInvoice.paid_total }}</strong></div>
        <div><span>Due</span><strong>BDT {{ selectedInvoice.due_total }}</strong></div>
      </section>

      <div class="inline-actions no-print">
        <button class="button primary" type="button" @click="printSelectedInvoice">Print Invoice</button>
        <button class="button ghost" type="button" @click="exportInvoice(selectedInvoice)">Export</button>
        <button class="button ghost" type="button" @click="selectedInvoice = null">Close</button>
      </div>
    </article>
  </section>
</template>
