{% extends "base.html" %}
{% from 'components/ui.html' import page_header %}

{% block content %}
{% set actions %}
<a href="{{ url_for('invoices.view_invoice', invoice_id=invoice.id) }}" class="btn btn-secondary">
    <i class="fas fa-arrow-left mr-2"></i>{{ _('Back') }}
</a>
<button type="button" onclick="showSendEmailModal()" class="btn bg-blue-500 text-white hover:bg-blue-600">
    <i class="fas fa-envelope mr-1"></i>{{ _('Send Email') }}
</button>
{% endset %}
{{ page_header('fas fa-file-invoice', _('Edit Invoice') ~ ' ' ~ invoice.invoice_number, subtitle_text=_('Update invoice details, items, and terms'), actions_html=actions, breadcrumbs=[{'text': _('Invoices'), 'url': url_for('invoices.list_invoices')}, {'text': _('Edit Invoice')}]) }}

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            <form method="POST" id="editInvoiceForm" novalidate data-validate-form>
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 min-w-0">
                    <div class="min-w-0">
                        <label for="client_name" class="form-label">{{ _('Client Name') }} *</label>
                        <input type="text" name="client_name" id="client_name" value="{{ invoice.client_name }}" required class="form-input">
                    </div>
                    <div class="min-w-0">
                        <label for="client_email" class="form-label">{{ _('Client Email') }}</label>
                        <input type="email" name="client_email" id="client_email" value="{{ invoice.client_email }}" class="form-input">
                    </div>
                    <div>
                        <label for="due_date" class="form-label">{{ _('Due Date') }} *</label>
                        <input type="date" name="due_date" id="due_date" value="{{ invoice.due_date.strftime('%Y-%m-%d') }}" required class="form-input user-date-input">
                    </div>
                    <div class="min-w-0">
                        <label for="tax_rate" class="form-label">{{ _('Tax Rate (%)') }}</label>
                        <input type="number" name="tax_rate" id="tax_rate" value="{{ invoice.tax_rate }}" step="0.01" class="form-input">
                    </div>
                    <div class="md:col-span-2">
                        <label for="client_address" class="form-label">{{ _('Client Address') }}</label>
                        <textarea name="client_address" id="client_address" rows="3" class="form-input">{{ invoice.client_address }}</textarea>
                    </div>
                    <div class="md:col-span-2 min-w-0">
                        <label for="buyer_reference" class="form-label">{{ _('Buyer reference (PEPPOL BT-10)') }}</label>
                        <input type="text" name="buyer_reference" id="buyer_reference" value="{{ invoice.buyer_reference or '' }}" class="form-input" placeholder="{{ _('Optional; used in PEPPOL UBL') }}">
                    </div>
                    <div class="md:col-span-2 min-w-0">
                        <label for="notes" class="form-label">{{ _('Notes') }}</label>
                        <textarea name="notes" id="notes" rows="3" class="form-input">{{ invoice.notes or '' }}</textarea>
                    </div>
                    <div class="md:col-span-2 min-w-0">
                        <label for="terms" class="form-label">{{ _('Terms') }}</label>
                        <textarea name="terms" id="terms" rows="3" class="form-input">{{ invoice.terms or '' }}</textarea>
                    </div>
                </div>

                <div class="mt-8 border-t border-border-light dark:border-border-dark pt-6">
                    <div class="flex items-center justify-between mb-4">
                        <div>
                            <h2 class="text-lg font-semibold flex items-center">
                                <i class="fas fa-file-invoice mr-2 text-blue-600"></i>
                                {{ _('Invoice Items') }}
                                <span id="items-count" class="ml-2 px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-full">0</span>
                            </h2>
                            <p class="text-sm text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Time-based services and hourly work') }}</p>
                        </div>
                        <button type="button" id="add-item" class="btn btn-primary shadow-sm">
                            <i class="fas fa-plus mr-2"></i>{{ _('Add Item') }}
                        </button>
                    </div>
                    
                    <!-- Items header (desktop) -->
                    <div class="hidden md:grid md:grid-cols-12 gap-3 mb-2 px-3 text-xs font-semibold text-text-muted-light dark:text-text-muted-dark uppercase">
                        <div class="md:col-span-2">{{ _('Project / Stock Item') }}</div>
                        <div class="md:col-span-2">{{ _('Task / Warehouse') }}</div>
                        <div class="md:col-span-3">{{ _('Description') }}</div>
                        <div class="md:col-span-2">{{ _('Quantity') }}</div>
                        <div class="md:col-span-2">{{ _('Unit Price') }}</div>
                        <div class="md:col-span-1 text-center">{{ _('Action') }}</div>
                    </div>
                    
                    <div id="invoice-items" class="space-y-2">
                        {% for item in invoice.items %}
                        <div class="grid grid-cols-1 md:grid-cols-12 gap-3 p-3 rounded-lg bg-blue-50/50 dark:bg-blue-950/20 border border-blue-200/50 dark:border-blue-800/50 invoice-item-row min-w-0 hover:shadow-sm transition" data-is-time-based="{{ 'true' if item.time_entry_ids else 'false' }}">
                            <input type="hidden" name="item_stock_item_id[]" value="{{ item.stock_item_id if item.stock_item_id else '' }}">
                            <input type="hidden" name="item_warehouse_id[]" value="{{ item.warehouse_id if item.warehouse_id else '' }}">
                            <input type="hidden" name="item_time_entry_ids[]" value="{{ item.time_entry_ids or '' }}">
                            {% if item.time_entry_ids %}
                            {# Time-based item: show Project and Task #}
                            <div class="md:col-span-2 min-w-0 flex flex-col justify-center">
                                <span class="text-sm text-text-light dark:text-text-dark py-2">{{ invoice.project.name if invoice.project else '-' }}</span>
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col justify-center">
                                <span class="text-sm text-text-light dark:text-text-dark py-2">{{ item.task_name_from_time_entries or _('Project hours') }}</span>
                            </div>
                            {% else %}
                            {# Stock/manual item: show Stock and Warehouse dropdowns #}
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <select class="form-input item-stock-select text-sm" data-row-index="{{ loop.index0 }}" title="{{ _('Select Stock Item') }}">
                                    <option value="">{{ _('None') }}</option>
                                    {% for stock_item in stock_items %}
                                    <option value="{{ stock_item.id }}" data-price="{{ stock_item.default_price or 0 }}" data-unit="{{ stock_item.unit }}" data-description="{{ stock_item.name }}" {% if item.stock_item_id == stock_item.id %}selected{% endif %}>{{ stock_item.sku }} - {{ stock_item.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <select class="form-input item-warehouse-select text-sm" data-row-index="{{ loop.index0 }}" title="{{ _('Select Warehouse') }}">
                                    <option value="">{{ _('None') }}</option>
                                    {% for warehouse in warehouses %}
                                    <option value="{{ warehouse.id }}" {% if item.warehouse_id == warehouse.id %}selected{% endif %}>{{ warehouse.code }} - {{ warehouse.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            {% endif %}
                            <div class="md:col-span-3 min-w-0 flex flex-col">
                                <input type="text" name="description[]" placeholder="{{ _('e.g., Web Development Services') }}" value="{{ item.description }}" class="form-input item-description" data-calc-trigger>
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                {% if item.time_entry_ids %}
                                <input type="number" name="quantity[]" placeholder="{{ _('Quantity') }}" value="{{ item.quantity }}" step="0.01" min="0" class="form-input item-quantity bg-gray-100 dark:bg-gray-800 cursor-not-allowed" readonly title="{{ _('Quantity is from logged hours and cannot be edited') }}">
                                {% else %}
                                <input type="number" name="quantity[]" placeholder="{{ _('Quantity') }}" value="{{ item.quantity }}" step="0.01" min="0" class="form-input item-quantity" data-calc-trigger>
                                {% endif %}
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <input type="number" name="unit_price[]" placeholder="{{ _('Unit Price') }}" value="{{ item.unit_price }}" step="0.01" min="0" class="form-input item-price" data-calc-trigger>
                            </div>
                            <div class="md:col-span-1 min-w-0 flex flex-col">
                                <button type="button" class="remove-item bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300 px-3 py-2 rounded hover:bg-rose-200 dark:hover:bg-rose-900/50 transition" title="{{ _('Remove item') }}">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    
                    <div id="items-subtotal" class="mt-3 p-3 bg-blue-50/30 dark:bg-blue-950/10 rounded-lg border border-blue-200/30 dark:border-blue-800/30">
                        <div class="flex justify-between items-center text-sm font-medium">
                            <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Items Subtotal') }}:</span>
                            <span class="text-lg font-bold text-blue-700 dark:text-blue-400">{{ invoice.currency_code }} <span id="items-subtotal-amount">0.00</span></span>
                        </div>
                    </div>
                </div>

                <div class="mt-8 border-t border-border-light dark:border-border-dark pt-6">
                    <div class="flex items-center justify-between mb-4">
                        <div>
                            <h2 class="text-lg font-semibold flex items-center">
                                <i class="fas fa-receipt mr-2 text-amber-600"></i>
                                {{ _('Expenses') }}
                                <span id="expenses-count" class="ml-2 px-2 py-0.5 text-xs bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 rounded-full">0</span>
                            </h2>
                            <p class="text-sm text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Billable expenses such as travel, meals, and materials') }}</p>
                        </div>
                        <button type="button" id="add-expense" class="btn bg-amber-600 text-white hover:bg-amber-700 shadow-sm">
                            <i class="fas fa-plus mr-2"></i>{{ _('Add Expense') }}
                        </button>
                    </div>
                    
                    <!-- Expenses header (desktop) -->
                    <div class="hidden md:grid md:grid-cols-12 gap-3 mb-2 px-3 text-xs font-semibold text-text-muted-light dark:text-text-muted-dark uppercase">
                        <div class="md:col-span-3">{{ _('Title') }}</div>
                        <div class="md:col-span-3">{{ _('Description') }}</div>
                        <div class="md:col-span-2">{{ _('Category') }}</div>
                        <div class="md:col-span-2">{{ _('Amount') }}</div>
                        <div class="md:col-span-1">{{ _('Date') }}</div>
                        <div class="md:col-span-1 text-center">{{ _('Action') }}</div>
                    </div>
                    
                    <div id="invoice-expenses" class="space-y-2">
                        {% for expense in invoice.expenses %}
                        <div class="grid grid-cols-1 md:grid-cols-12 gap-3 p-3 rounded-lg bg-amber-50/50 dark:bg-amber-950/20 border border-amber-200/50 dark:border-amber-800/50 invoice-expense-row min-w-0 hover:shadow-sm transition">
                            <input type="hidden" name="expense_id[]" value="{{ expense.id }}">
                            <div class="md:col-span-3 min-w-0 flex flex-col">
                                <input type="text" name="expense_title[]" placeholder="{{ _('e.g., Travel to Client Meeting') }}" value="{{ expense.title }}" class="form-input" data-calc-trigger readonly title="{{ _('Linked expense - title cannot be edited') }}">
                            </div>
                            <div class="md:col-span-3 min-w-0 flex flex-col">
                                <input type="text" name="expense_description[]" placeholder="{{ _('Description') }}" value="{{ expense.description or '' }}" class="form-input" readonly title="{{ _('Linked expense - description cannot be edited') }}">
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <select name="expense_category[]" class="form-input" disabled title="{{ _('Linked expense - category cannot be edited') }}">
                                    <option value="travel" {% if expense.category == 'travel' %}selected{% endif %}>{{ _('Travel') }}</option>
                                    <option value="meals" {% if expense.category == 'meals' %}selected{% endif %}>{{ _('Meals') }}</option>
                                    <option value="accommodation" {% if expense.category == 'accommodation' %}selected{% endif %}>{{ _('Accommodation') }}</option>
                                    <option value="supplies" {% if expense.category == 'supplies' %}selected{% endif %}>{{ _('Supplies') }}</option>
                                    <option value="software" {% if expense.category == 'software' %}selected{% endif %}>{{ _('Software') }}</option>
                                    <option value="equipment" {% if expense.category == 'equipment' %}selected{% endif %}>{{ _('Equipment') }}</option>
                                    <option value="services" {% if expense.category == 'services' %}selected{% endif %}>{{ _('Services') }}</option>
                                    <option value="marketing" {% if expense.category == 'marketing' %}selected{% endif %}>{{ _('Marketing') }}</option>
                                    <option value="training" {% if expense.category == 'training' %}selected{% endif %}>{{ _('Training') }}</option>
                                    <option value="other" {% if expense.category == 'other' %}selected{% endif %}>{{ _('Other') }}</option>
                                </select>
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <input type="number" name="expense_amount[]" placeholder="{{ _('Amount') }}" value="{{ expense.total_amount }}" step="0.01" min="0" class="form-input expense-amount" data-calc-trigger readonly title="{{ _('Linked expense - amount cannot be edited') }}">
                            </div>
                            <div class="md:col-span-1 min-w-0 flex flex-col">
                                <input type="date" name="expense_date[]" value="{{ expense.expense_date.strftime('%Y-%m-%d') if expense.expense_date else '' }}" class="form-input user-date-input text-xs" readonly title="{{ _('Linked expense - date cannot be edited') }}">
                            </div>
                            <div class="md:col-span-1 min-w-0 flex flex-col">
                                <button type="button" class="remove-expense bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300 px-3 py-2 rounded hover:bg-rose-200 dark:hover:bg-rose-900/50 transition" title="{{ _('Unlink expense from invoice') }}">
                                    <i class="fas fa-unlink"></i>
                                </button>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    
                    <div id="expenses-subtotal" class="mt-3 p-3 bg-amber-50/30 dark:bg-amber-950/10 rounded-lg border border-amber-200/30 dark:border-amber-800/30">
                        <div class="flex justify-between items-center text-sm font-medium">
                            <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Expenses Subtotal') }}:</span>
                            <span class="text-lg font-bold text-amber-700 dark:text-amber-400">{{ invoice.currency_code }} <span id="expenses-subtotal-amount">0.00</span></span>
                        </div>
                    </div>
                </div>

                <div class="mt-8 border-t border-border-light dark:border-border-dark pt-6">
                    <div class="flex items-center justify-between mb-4">
                        <div>
                            <h2 class="text-lg font-semibold flex items-center">
                                <i class="fas fa-box mr-2 text-emerald-600"></i>
                                {{ _('Extra Goods') }}
                                <span id="goods-count" class="ml-2 px-2 py-0.5 text-xs bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 rounded-full">0</span>
                            </h2>
                            <p class="text-sm text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Products, materials, licenses, and other goods') }}</p>
                        </div>
                        <button type="button" id="add-good" class="btn bg-emerald-600 text-white hover:bg-emerald-700 shadow-sm">
                            <i class="fas fa-plus mr-2"></i>{{ _('Add Good') }}
                        </button>
                    </div>
                    
                    <!-- Goods header (desktop) -->
                    <div class="hidden md:grid md:grid-cols-12 gap-3 mb-2 px-3 text-xs font-semibold text-text-muted-light dark:text-text-muted-dark uppercase">
                        <div class="md:col-span-2">{{ _('Name') }}</div>
                        <div class="md:col-span-2">{{ _('Description') }}</div>
                        <div class="md:col-span-2">{{ _('Category') }}</div>
                        <div class="md:col-span-2">{{ _('Qty') }}</div>
                        <div class="md:col-span-2">{{ _('Price') }}</div>
                        <div class="md:col-span-1">{{ _('SKU') }}</div>
                        <div class="md:col-span-1 text-center">{{ _('Action') }}</div>
                    </div>
                    
                    <div id="invoice-goods" class="space-y-2">
                        {% for good in invoice.extra_goods %}
                        <div class="grid grid-cols-1 md:grid-cols-12 gap-3 p-3 rounded-lg bg-emerald-50/50 dark:bg-emerald-950/20 border border-emerald-200/50 dark:border-emerald-800/50 invoice-good-row min-w-0 hover:shadow-sm transition">
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <input type="text" name="good_name[]" placeholder="{{ _('e.g., Software License') }}" value="{{ good.name }}" class="form-input" data-calc-trigger>
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <input type="text" name="good_description[]" placeholder="{{ _('Description') }}" value="{{ good.description or '' }}" class="form-input">
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <select name="good_category[]" class="form-input">
                                    <option value="product" {% if good.category == 'product' %}selected{% endif %}>{{ _('Product') }}</option>
                                    <option value="service" {% if good.category == 'service' %}selected{% endif %}>{{ _('Service') }}</option>
                                    <option value="material" {% if good.category == 'material' %}selected{% endif %}>{{ _('Material') }}</option>
                                    <option value="license" {% if good.category == 'license' %}selected{% endif %}>{{ _('License') }}</option>
                                    <option value="other" {% if good.category == 'other' %}selected{% endif %}>{{ _('Other') }}</option>
                                </select>
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <input type="number" name="good_quantity[]" placeholder="{{ _('Qty') }}" value="{{ good.quantity }}" step="0.01" min="0" class="form-input good-quantity" data-calc-trigger>
                            </div>
                            <div class="md:col-span-2 min-w-0 flex flex-col">
                                <input type="number" name="good_unit_price[]" placeholder="{{ _('Price') }}" value="{{ good.unit_price }}" step="0.01" min="0" class="form-input good-price" data-calc-trigger>
                            </div>
                            <div class="md:col-span-1 min-w-0 flex flex-col">
                                <input type="text" name="good_sku[]" placeholder="{{ _('SKU') }}" value="{{ good.sku or '' }}" class="form-input text-xs">
                            </div>
                            <div class="md:col-span-1 min-w-0 flex flex-col">
                                <button type="button" class="remove-good bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300 px-3 py-2 rounded hover:bg-rose-200 dark:hover:bg-rose-900/50 transition" title="{{ _('Remove good') }}">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                    
                    <div id="goods-subtotal" class="mt-3 p-3 bg-emerald-50/30 dark:bg-emerald-950/10 rounded-lg border border-emerald-200/30 dark:border-emerald-800/30">
                        <div class="flex justify-between items-center text-sm font-medium">
                            <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Goods Subtotal') }}:</span>
                            <span class="text-lg font-bold text-emerald-700 dark:text-emerald-400">{{ invoice.currency_code }} <span id="goods-subtotal-amount">0.00</span></span>
                        </div>
                    </div>
                </div>

                <div class="mt-6 flex flex-wrap justify-end gap-3 border-t border-border-light dark:border-border-dark pt-4">
                    <a href="{{ url_for('invoices.view_invoice', invoice_id=invoice.id) }}" class="btn btn-secondary">{{ _('Cancel') }}</a>
                    <button type="submit" class="btn btn-primary">{{ _('Save Changes') }}</button>
                </div>
            </form>
        </div>
    </div>

    <div class="space-y-4">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm sticky top-4">
            <h3 class="text-lg font-semibold mb-4 flex items-center">
                <i class="fas fa-calculator mr-2 text-primary"></i>
                {{ _('Live Preview') }}
            </h3>
            
            <div class="space-y-4">
                <!-- Invoice Info -->
                <div class="pb-4 border-b border-border-light dark:border-border-dark">
                    <div class="grid grid-cols-2 gap-3 text-sm">
                        <div>
                            <div class="text-text-muted-light dark:text-text-muted-dark text-xs">{{ _('Issue Date') }}</div>
                            <div class="font-medium">{{ invoice.issue_date|format_date if invoice.issue_date else '-' }}</div>
                        </div>
                        <div>
                            <div class="text-text-muted-light dark:text-text-muted-dark text-xs">{{ _('Status') }}</div>
                            <div>
                                <span class="px-2 py-0.5 text-xs rounded {% if invoice.status == 'paid' %}bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300{% elif invoice.status == 'sent' %}bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300{% elif invoice.status == 'overdue' %}bg-rose-100 dark:bg-rose-900/30 text-rose-700 dark:text-rose-300{% else %}bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300{% endif %}">
                                    {{ invoice.status|capitalize }}
                                </span>
                            </div>
                        </div>
                        <div>
                            <div class="text-text-muted-light dark:text-text-muted-dark text-xs">{{ _('Payment') }}</div>
                            <div>
                                <span class="px-2 py-0.5 text-xs rounded {% if invoice.payment_status == 'fully_paid' %}bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300{% elif invoice.payment_status == 'partially_paid' %}bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300{% else %}bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300{% endif %}">
                                    {{ invoice.payment_status.replace('_',' ')|capitalize }}
                                </span>
                            </div>
                        </div>
                        <div>
                            <div class="text-text-muted-light dark:text-text-muted-dark text-xs">{{ _('Currency') }}</div>
                            <div class="font-medium">{{ invoice.currency_code }}</div>
                        </div>
                    </div>
                </div>
                
                <!-- Calculation Preview -->
                <div class="space-y-3">
                    <div class="flex justify-between text-sm">
                        <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Items') }} (<span id="preview-items-count">0</span>)</span>
                        <span class="font-medium" id="preview-items-total">0.00</span>
                    </div>
                    <div class="flex justify-between text-sm">
                        <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Expenses') }} (<span id="preview-expenses-count">0</span>)</span>
                        <span class="font-medium" id="preview-expenses-total">0.00</span>
                    </div>
                    <div class="flex justify-between text-sm">
                        <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Goods') }} (<span id="preview-goods-count">0</span>)</span>
                        <span class="font-medium" id="preview-goods-total">0.00</span>
                    </div>
                    <div class="flex justify-between text-sm pt-3 border-t border-border-light dark:border-border-dark">
                        <span class="font-medium">{{ _('Subtotal') }}</span>
                        <span class="font-semibold" id="preview-subtotal">0.00</span>
                    </div>
                    <div class="flex justify-between text-sm">
                        <span class="text-text-muted-light dark:text-text-muted-dark">
                            {{ _('Tax') }} (<span id="preview-tax-rate">{{ '%.2f'|format(invoice.tax_rate) }}</span>%)
                        </span>
                        <span class="font-medium" id="preview-tax-amount">0.00</span>
                    </div>
                    <div class="flex justify-between items-center pt-3 border-t-2 border-primary">
                        <span class="text-lg font-bold">{{ _('Total') }}</span>
                        <span class="text-2xl font-bold text-primary" id="preview-total">0.00</span>
                    </div>
                </div>
                
                <!-- Payment Info -->
                <div class="pt-4 border-t border-border-light dark:border-border-dark space-y-2 text-sm">
                    <div class="flex justify-between">
                        <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Amount Paid') }}</span>
                        <span class="font-semibold text-emerald-600 dark:text-emerald-400">{{ '%.2f'|format(invoice.amount_paid or 0) }}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-text-muted-light dark:text-text-muted-dark">{{ _('Outstanding') }}</span>
                        <span class="font-semibold" id="preview-outstanding">{{ '%.2f'|format(invoice.outstanding_amount) }}</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm">
            <h3 class="text-lg font-semibold mb-3">{{ _('Quick Actions') }}</h3>
            <div class="grid grid-cols-1 gap-2">
                <a href="{{ url_for('invoices.generate_from_time', invoice_id=invoice.id) }}" class="btn btn-sm border border-primary text-primary hover:bg-primary/10"><i class="fas fa-clock mr-2"></i>{{ _('Generate from Time/Costs') }}</a>
                <a href="{{ url_for('payments.create_payment', invoice_id=invoice.id) }}" class="btn btn-sm bg-emerald-600 text-white hover:bg-emerald-700"><i class="fas fa-cash-register mr-2"></i>{{ _('Record Payment') }}</a>
                <a href="{{ url_for('invoices.export_invoice_pdf', invoice_id=invoice.id) }}" class="btn btn-sm btn-secondary"><i class="fas fa-file-pdf mr-2"></i>{{ _('Export PDF') }}</a>
                <a href="{{ url_for('invoices.export_invoice_csv', invoice_id=invoice.id) }}" class="btn btn-sm btn-secondary"><i class="fas fa-file-csv mr-2"></i>{{ _('Export CSV') }}</a>
                <a href="{{ url_for('invoices.duplicate_invoice', invoice_id=invoice.id) }}" class="btn btn-sm btn-secondary"><i class="fas fa-clone mr-2"></i>{{ _('Duplicate Invoice') }}</a>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts_extra %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const itemsContainer = document.getElementById('invoice-items');
    const expensesContainer = document.getElementById('invoice-expenses');
    const goodsContainer = document.getElementById('invoice-goods');
    const taxRateInput = document.getElementById('tax_rate');
    
    // Calculate totals function
    function calculateTotals() {
        // Calculate items
        let itemsTotal = 0;
        let itemsCount = 0;
        document.querySelectorAll('.invoice-item-row').forEach(row => {
            const qty = parseFloat(row.querySelector('.item-quantity')?.value || 0);
            const price = parseFloat(row.querySelector('.item-price')?.value || 0);
            if (qty > 0 && price > 0) {
                itemsTotal += qty * price;
                itemsCount++;
            }
        });
        
        // Calculate expenses
        let expensesTotal = 0;
        let expensesCount = 0;
        document.querySelectorAll('.invoice-expense-row').forEach(row => {
            const amount = parseFloat(row.querySelector('.expense-amount')?.value || 0);
            if (amount > 0) {
                expensesTotal += amount;
                expensesCount++;
            }
        });
        
        // Calculate goods
        let goodsTotal = 0;
        let goodsCount = 0;
        document.querySelectorAll('.invoice-good-row').forEach(row => {
            const qty = parseFloat(row.querySelector('.good-quantity')?.value || 0);
            const price = parseFloat(row.querySelector('.good-price')?.value || 0);
            if (qty > 0 && price > 0) {
                goodsTotal += qty * price;
                goodsCount++;
            }
        });
        
        // Calculate subtotal and tax
        const subtotal = itemsTotal + expensesTotal + goodsTotal;
        const taxRate = parseFloat(taxRateInput?.value || 0);
        const taxAmount = subtotal * (taxRate / 100);
        const total = subtotal + taxAmount;
        
        // Calculate outstanding
        const amountPaid = parseFloat('{{ invoice.amount_paid or 0 }}');
        const outstanding = Math.max(0, total - amountPaid);
        
        // Update displays
        document.getElementById('items-count').textContent = itemsCount;
        document.getElementById('expenses-count').textContent = expensesCount;
        document.getElementById('goods-count').textContent = goodsCount;
        document.getElementById('items-subtotal-amount').textContent = itemsTotal.toFixed(2);
        document.getElementById('expenses-subtotal-amount').textContent = expensesTotal.toFixed(2);
        document.getElementById('goods-subtotal-amount').textContent = goodsTotal.toFixed(2);
        
        // Update preview panel
        document.getElementById('preview-items-count').textContent = itemsCount;
        document.getElementById('preview-expenses-count').textContent = expensesCount;
        document.getElementById('preview-goods-count').textContent = goodsCount;
        document.getElementById('preview-items-total').textContent = itemsTotal.toFixed(2);
        document.getElementById('preview-expenses-total').textContent = expensesTotal.toFixed(2);
        document.getElementById('preview-goods-total').textContent = goodsTotal.toFixed(2);
        document.getElementById('preview-subtotal').textContent = subtotal.toFixed(2);
        document.getElementById('preview-tax-rate').textContent = taxRate.toFixed(2);
        document.getElementById('preview-tax-amount').textContent = taxAmount.toFixed(2);
        document.getElementById('preview-total').textContent = total.toFixed(2);
        document.getElementById('preview-outstanding').textContent = outstanding.toFixed(2);
    }
    
    // Stock items and warehouses data
    const stockItems = {{ stock_items_json | safe if stock_items_json else '[]' }};
    const warehouses = {{ warehouses_json | safe if warehouses_json else '[]' }};
    
    // Handle stock item selection
    function setupStockItemHandlers() {
        document.querySelectorAll('.item-stock-select').forEach(select => {
            select.addEventListener('change', function() {
                const row = this.closest('.invoice-item-row');
                const stockItemId = this.value;
                const selectedOption = this.options[this.selectedIndex];
                const hiddenStockInput = row.querySelector('input[name="item_stock_item_id[]"]');
                
                hiddenStockInput.value = stockItemId || '';
                
                if (stockItemId && selectedOption) {
                    const price = parseFloat(selectedOption.dataset.price || 0);
                    const description = selectedOption.dataset.description || '';
                    
                    // Auto-populate fields
                    if (description && !row.querySelector('.item-description').value) {
                        row.querySelector('.item-description').value = description;
                    }
                    if (price > 0 && !row.querySelector('.item-price').value) {
                        row.querySelector('.item-price').value = price.toFixed(2);
                    }
                    calculateTotals();
                }
            });
        });
    }
    
    // Add item button
    const addBtn = document.getElementById('add-item');
    addBtn && addBtn.addEventListener('click', function() {
        const row = document.createElement('div');
        row.className = 'grid grid-cols-1 md:grid-cols-12 gap-3 p-3 rounded-lg bg-blue-50/50 dark:bg-blue-950/20 border border-blue-200/50 dark:border-blue-800/50 invoice-item-row hover:shadow-sm transition';
        
        // Build stock items dropdown
        let stockItemsHtml = '<option value="">{{ _("None") }}</option>';
        if (stockItems && Array.isArray(stockItems)) {
            stockItems.forEach(item => {
                const price = item.default_price || 0;
                const unit = item.unit || '';
                const desc = item.description || item.name || '';
                stockItemsHtml += '<option value="' + item.id + '" data-price="' + price + '" data-unit="' + unit + '" data-description="' + desc.replace(/"/g, '&quot;') + '">' + item.sku + ' - ' + item.name + '</option>';
            });
        }
        
        // Build warehouses dropdown
        let warehousesHtml = '<option value="">{{ _("None") }}</option>';
        if (warehouses && Array.isArray(warehouses)) {
            warehouses.forEach(wh => {
                warehousesHtml += '<option value="' + wh.id + '">' + wh.code + ' - ' + wh.name + '</option>';
            });
        }
        
        row.innerHTML = `
            <input type="hidden" name="item_stock_item_id[]" value="">
            <input type="hidden" name="item_warehouse_id[]" value="">
            <input type="hidden" name="item_time_entry_ids[]" value="">
            <div class="md:col-span-2 min-w-0 flex flex-col">
                <select class="form-input item-stock-select text-sm">
                    ${stockItemsHtml}
                </select>
            </div>
            <div class="md:col-span-2 min-w-0 flex flex-col">
                <select class="form-input item-warehouse-select text-sm">
                    ${warehousesHtml}
                </select>
            </div>
            <div class="md:col-span-3 min-w-0 flex flex-col">
                <input type="text" name="description[]" placeholder="{{ _('e.g., Web Development Services') }}" class="form-input item-description" data-calc-trigger>
            </div>
            <div class="md:col-span-2 min-w-0 flex flex-col">
                <input type="number" name="quantity[]" placeholder="{{ _('Quantity') }}" value="1" step="0.01" min="0" class="form-input item-quantity" data-calc-trigger>
            </div>
            <div class="md:col-span-2 min-w-0 flex flex-col">
                <input type="number" name="unit_price[]" placeholder="{{ _('Unit Price') }}" step="0.01" min="0" class="form-input item-price" data-calc-trigger>
            </div>
            <div class="md:col-span-1 min-w-0 flex flex-col">
                <button type="button" class="remove-item bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300 px-3 py-2 rounded hover:bg-rose-200 dark:hover:bg-rose-900/50 transition" title="{{ _('Remove item') }}">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        `;
        itemsContainer.appendChild(row);
        
        // Setup handlers for new row
        const stockSelect = row.querySelector('.item-stock-select');
        stockSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const hiddenStockInput = row.querySelector('input[name="item_stock_item_id[]"]');
            hiddenStockInput.value = this.value || '';
            
            if (this.value && selectedOption) {
                const price = parseFloat(selectedOption.dataset.price || 0);
                const description = selectedOption.dataset.description || '';
                if (description) row.querySelector('.item-description').value = description;
                if (price > 0) row.querySelector('.item-price').value = price.toFixed(2);
                calculateTotals();
            }
        });
        
        const warehouseSelect = row.querySelector('.item-warehouse-select');
        warehouseSelect.addEventListener('change', function() {
            const hiddenWarehouseInput = row.querySelector('input[name="item_warehouse_id[]"]');
            hiddenWarehouseInput.value = this.value || '';
        });
        
        // Setup calculation triggers
        row.querySelectorAll('[data-calc-trigger]').forEach(input => {
            input.addEventListener('input', calculateTotals);
        });
        
        calculateTotals();
        setupStockItemHandlers();
        row.querySelector('.item-stock-select').focus();
    });
    
    // Initialize stock item handlers for existing rows
    setupStockItemHandlers();
    
    // Setup warehouse handlers
    document.querySelectorAll('.item-warehouse-select').forEach(select => {
        select.addEventListener('change', function() {
            const row = this.closest('.invoice-item-row');
            const hiddenWarehouseInput = row.querySelector('input[name="item_warehouse_id[]"]');
            hiddenWarehouseInput.value = this.value || '';
        });
    });

    // Add good button
    const addGoodBtn = document.getElementById('add-good');
    addGoodBtn && addGoodBtn.addEventListener('click', function() {
        const row = document.createElement('div');
        row.className = 'grid grid-cols-1 md:grid-cols-12 gap-3 p-3 rounded-lg bg-emerald-50/50 dark:bg-emerald-950/20 border border-emerald-200/50 dark:border-emerald-800/50 invoice-good-row min-w-0 hover:shadow-sm transition space-y-2';
        row.innerHTML = `
            <div class="md:col-span-2 min-w-0 flex flex-col">
                <input type="text" name="good_name[]" placeholder="{{ _('e.g., Software License') }}" class="form-input" data-calc-trigger>
            </div>
            <div class="md:col-span-2 min-w-0 flex flex-col">
                <input type="text" name="good_description[]" placeholder="{{ _('Description') }}" class="form-input">
            </div>
            <div class="md:col-span-2 min-w-0 flex flex-col">
                <select name="good_category[]" class="form-input">
                    <option value="product">{{ _('Product') }}</option>
                    <option value="service">{{ _('Service') }}</option>
                    <option value="material">{{ _('Material') }}</option>
                    <option value="license">{{ _('License') }}</option>
                    <option value="other">{{ _('Other') }}</option>
                </select>
            </div>
            <div class="md:col-span-2 min-w-0 flex flex-col">
                <input type="number" name="good_quantity[]" placeholder="{{ _('Qty') }}" value="1" step="0.01" min="0" class="form-input good-quantity" data-calc-trigger>
            </div>
            <div class="md:col-span-2 min-w-0 flex flex-col">
                <input type="number" name="good_unit_price[]" placeholder="{{ _('Price') }}" step="0.01" min="0" class="form-input good-price" data-calc-trigger>
            </div>
            <div class="md:col-span-1 min-w-0 flex flex-col">
                <input type="text" name="good_sku[]" placeholder="{{ _('SKU') }}" class="form-input text-xs">
            </div>
            <div class="md:col-span-1 min-w-0 flex flex-col">
                <button type="button" class="remove-good bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300 px-3 py-2 rounded hover:bg-rose-200 dark:hover:bg-rose-900/50 transition" title="{{ _('Remove good') }}">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        `;
        goodsContainer.appendChild(row);
        calculateTotals();
        row.querySelector('[name="good_name[]"]').focus();
    });

    // Remove item handler
    itemsContainer && itemsContainer.addEventListener('click', function(e) {
        if (e.target.closest('.remove-item')) {
            const row = e.target.closest('.invoice-item-row');
            if (row) {
                row.style.opacity = '0.5';
                row.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    row.remove();
                    calculateTotals();
                }, 200);
            }
        }
    });

    // Add expense button - redirect to generate from time page which includes expenses
    const addExpenseBtn = document.getElementById('add-expense');
    addExpenseBtn && addExpenseBtn.addEventListener('click', function() {
        window.location.href = '{{ url_for("invoices.generate_from_time", invoice_id=invoice.id) }}';
    });

    // Remove expense handler (unlink from invoice)
    expensesContainer && expensesContainer.addEventListener('click', async function(e) {
        if (e.target.closest('.remove-expense')) {
            const row = e.target.closest('.invoice-expense-row');
            if (row) {
                const confirmed = await showConfirm(
                    '{{ _("Are you sure you want to unlink this expense from the invoice?") }}',
                    {
                        title: '{{ _("Unlink Expense") }}',
                        confirmText: '{{ _("Unlink") }}',
                        cancelText: '{{ _("Cancel") }}',
                        variant: 'warning'
                    }
                );
                if (confirmed) {
                    row.style.opacity = '0.5';
                    row.style.transform = 'scale(0.95)';
                    setTimeout(() => {
                        row.remove();
                        calculateTotals();
                    }, 200);
                }
            }
        }
    });

    // Remove good handler
    goodsContainer && goodsContainer.addEventListener('click', function(e) {
        if (e.target.closest('.remove-good')) {
            const row = e.target.closest('.invoice-good-row');
            if (row) {
                row.style.opacity = '0.5';
                row.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    row.remove();
                    calculateTotals();
                }, 200);
            }
        }
    });
    
    // Live calculation on input changes
    document.addEventListener('input', function(e) {
        if (e.target.hasAttribute('data-calc-trigger') || e.target.id === 'tax_rate') {
            calculateTotals();
        }
    });
    
    // Initial calculation
    calculateTotals();
    
    // Form validation before submit
    const form = document.getElementById('editInvoiceForm');
    form && form.addEventListener('submit', function(e) {
        const itemRows = document.querySelectorAll('.invoice-item-row');
        const expenseRows = document.querySelectorAll('.invoice-expense-row');
        const goodRows = document.querySelectorAll('.invoice-good-row');
        
        if (itemRows.length === 0 && expenseRows.length === 0 && goodRows.length === 0) {
            e.preventDefault();
            alert('{{ _("Please add at least one item, expense, or extra good to the invoice") }}');
            return false;
        }
    });
});
</script>

<!-- Send Email Modal -->
<div id="sendEmailModal" class="hidden fixed inset-0 bg-black/50 overflow-y-auto h-full w-full z-50">
  <div class="relative top-20 mx-auto p-5 max-w-sm w-full sm:w-96 bg-card-light dark:bg-card-dark rounded-xl shadow-xl border border-border-light dark:border-border-dark mx-4 sm:mx-auto">
    <div class="mt-3">
      <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">Send Invoice via Email</h3>
      <form id="sendEmailForm" onsubmit="sendInvoiceEmail(event)">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <div class="mb-4">
          <label for="recipient_email" class="form-label">Recipient Email *</label>
          <input type="email" id="recipient_email" name="recipient_email" value="{{ invoice.client_email }}" required class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
        </div>
        <div class="mb-4">
          <label for="email_template_id" class="form-label">Email Template (Optional)</label>
          <select id="email_template_id" name="email_template_id" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100">
            <option value="">Default Template</option>
            {% for template in email_templates %}
            <option value="{{ template.id }}">{{ template.name }}</option>
            {% endfor %}
          </select>
        </div>
        <div class="mb-4">
          <label for="custom_message" class="form-label">{{ _('Custom Message') }} ({{ _('Optional') }})</label>
          <textarea id="custom_message" name="custom_message" rows="4" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"></textarea>
        </div>
        <div class="flex flex-wrap justify-end gap-3">
          <button type="button" onclick="hideSendEmailModal()" class="btn btn-secondary">Cancel</button>
          <button type="submit" class="btn bg-blue-500 text-white hover:bg-blue-600">Send Email</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function showSendEmailModal() {
  const modal = document.getElementById('sendEmailModal');
  if (modal) modal.classList.remove('hidden');
}

function hideSendEmailModal() {
  const modal = document.getElementById('sendEmailModal');
  if (modal) modal.classList.add('hidden');
}

function sendInvoiceEmail(event) {
  event.preventDefault();
  const form = event.target;
  const formData = new FormData(form);
  
  // Show loading state
  const submitBtn = form.querySelector('button[type="submit"]');
  const originalText = submitBtn.textContent;
  submitBtn.disabled = true;
  submitBtn.textContent = 'Sending...';
  
  fetch("{{ url_for('invoices.send_invoice_email_route', invoice_id=invoice.id) }}", {
    method: 'POST',
    body: formData
  })
  .then(async response => {
    // Check content type to determine how to parse
    const contentType = response.headers.get('content-type') || '';
    const isJson = contentType.includes('application/json');
    
    // Always try JSON first if content-type suggests it, otherwise read as text
    if (isJson) {
      const data = await response.json();
      // Handle both success and error responses
      if (!response.ok) {
        return { success: false, error: data.error || data.message || `HTTP ${response.status}: ${response.statusText}` };
      }
      return data;
    } else {
      // Not JSON, read as text (only once)
      const text = await response.text();
      if (!response.ok) {
        throw new Error(text || `HTTP ${response.status}: ${response.statusText}`);
      }
      // If successful but not JSON, return error format
      return { success: false, error: text || 'Unexpected response format' };
    }
  })
  .then(data => {
    if (data.success) {
      if (window.toastManager) {
        window.toastManager.success('Invoice email sent successfully!');
      } else {
        alert('Invoice email sent successfully!');
      }
      hideSendEmailModal();
      // Optionally reload the page to show updated status
      setTimeout(() => window.location.reload(), 1000);
    } else {
      const errorMsg = data.error || 'Failed to send email';
      console.error('Email send error:', errorMsg);
      if (window.toastManager) {
        window.toastManager.error('Error: ' + errorMsg);
      } else {
        alert('Error: ' + errorMsg);
      }
      submitBtn.disabled = false;
      submitBtn.textContent = originalText;
    }
  })
  .catch(error => {
    console.error('Email send error:', error);
    const errorMsg = error.message || 'Failed to send email. Please check server logs for details.';
    if (window.toastManager) {
      window.toastManager.error(errorMsg);
    } else {
      alert(errorMsg);
    }
    submitBtn.disabled = false;
    submitBtn.textContent = originalText;
  });
}
</script>
{% endblock %}
