{% extends "base.html" %}

{% block title %}{{ _('Invoices') }} - TimeTracker{% endblock %}

{% block content %}
<div class="container-fluid">
	{% from "_components.html" import page_header %}
	<div class="row">
		<div class="col-12">
			{% set actions %}
			<a href="{{ url_for('invoices.create_invoice') }}" class="btn-header btn-primary">
				<i class="fas fa-plus"></i> {{ _('Create Invoice') }}
			</a>
			{% endset %}
			{{ page_header('fas fa-file-invoice-dollar', _('Invoices'), _('Billing overview') ~ ' • ' ~ summary.total_invoices ~ ' ' ~ _('total'), actions) }}
		</div>
	</div>

	<!-- Enhanced Summary Cards -->
	<div class="row mb-4">
		<div class="col-md-3 col-sm-6 mb-3">
			<div class="card border-0 shadow-sm h-100 summary-card">
				<div class="card-body p-3">
					<div class="d-flex align-items-center">
						<div class="flex-shrink-0">
							<div class="summary-icon bg-primary bg-opacity-10 text-primary">
								<i class="fas fa-file-invoice"></i>
							</div>
						</div>
						<div class="flex-grow-1 ms-3">
							<div class="summary-label">{{ _('Total Invoices') }}</div>
							<div class="summary-value">{{ summary.total_invoices }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div class="col-md-3 col-sm-6 mb-3">
			<div class="card border-0 shadow-sm h-100 summary-card">
				<div class="card-body p-3">
					<div class="d-flex align-items-center">
						<div class="flex-shrink-0">
							<div class="summary-icon bg-success bg-opacity-10 text-success">
								<i class="fas fa-dollar-sign"></i>
							</div>
						</div>
						<div class="flex-grow-1 ms-3">
							<div class="summary-label">{{ _('Total Amount') }}</div>
							<div class="summary-value">{{ "%.2f"|format(summary.total_amount) }} {{ currency }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div class="col-md-3 col-sm-6 mb-3">
			<div class="card border-0 shadow-sm h-100 summary-card">
				<div class="card-body p-3">
					<div class="d-flex align-items-center">
						<div class="flex-shrink-0">
							<div class="summary-icon bg-info bg-opacity-10 text-info">
								<i class="fas fa-clock"></i>
							</div>
						</div>
						<div class="flex-grow-1 ms-3">
							<div class="summary-label">{{ _('Outstanding') }}</div>
							<div class="summary-value">{{ "%.2f"|format(summary.outstanding_amount) }} {{ currency }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div class="col-md-3 col-sm-6 mb-3">
			<div class="card border-0 shadow-sm h-100 summary-card">
				<div class="card-body p-3">
					<div class="d-flex align-items-center">
						<div class="flex-shrink-0">
							<div class="summary-icon bg-warning bg-opacity-10 text-warning">
								<i class="fas fa-exclamation-triangle"></i>
							</div>
						</div>
						<div class="flex-grow-1 ms-3">
							<div class="summary-label">{{ _('Overdue') }}</div>
							<div class="summary-value">{{ "%.2f"|format(summary.overdue_amount) }} {{ currency }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- Enhanced Invoices Table -->
	<div class="card shadow-sm border-0">
		<div class="card-header bg-white py-3">
			<div class="d-flex justify-content-between align-items-center">
				<h6 class="m-0 font-weight-bold text-primary">
					<i class="fas fa-list me-2"></i>{{ _('All Invoices') }}
				</h6>
				<div class="d-flex gap-2">
					<div class="input-group input-group-sm" style="width: 250px;">
						<span class="input-group-text bg-light border-end-0">
							<i class="fas fa-search text-muted"></i>
						</span>
						<input type="text" class="form-control border-start-0" id="searchInput" 
							   placeholder="{{ _('Search invoices...') }}">
					</div>
				</div>
			</div>
		</div>
		<div class="card-body p-0">
			{% if invoices %}
				<div class="table-responsive">
					<table class="table table-hover mb-0" id="invoicesTable">
						<thead class="table-light">
							<tr>
								<th class="border-0">{{ _('Invoice #') }}</th>
								<th class="border-0">{{ _('Client') }}</th>
								<th class="border-0">{{ _('Project') }}</th>
								<th class="border-0">{{ _('Issue Date') }}</th>
								<th class="border-0">{{ _('Due Date') }}</th>
								<th class="border-0">{{ _('Amount') }}</th>
								<th class="border-0">{{ _('Status') }}</th>
								<th class="border-0">{{ _('Payment') }}</th>
								<th class="border-0 text-center">{{ _('Actions') }}</th>
							</tr>
						</thead>
						<tbody>
							{% for invoice in invoices %}
							<tr class="invoice-row" data-status="{{ invoice.status }}">
								<td class="align-middle">
									<div class="d-flex align-items-center">
										<div class="invoice-number-badge me-2">
											{{ invoice.invoice_number }}
										</div>
									</div>
								</td>
								<td class="align-middle">
									<div class="client-info">
										<div class="client-name">{{ invoice.client_name }}</div>
										{% if invoice.client_email %}
										<small class="text-muted">{{ invoice.client_email }}</small>
										{% endif %}
									</div>
								</td>
								<td class="align-middle">
									<span class="project-badge">{{ invoice.project.name }}</span>
								</td>
								<td class="align-middle">
									<div class="date-info">
										<div class="date-value">{{ invoice.issue_date.strftime('%b %d, %Y') }}</div>
										<small class="text-muted">{{ invoice.issue_date.strftime('%Y-%m-%d') }}</small>
									</div>
								</td>
								<td class="align-middle">
									{% if invoice.is_overdue %}
										<div class="due-date overdue">
											<div class="date-value text-danger">
												{{ invoice.due_date.strftime('%b %d, %Y') }}
											</div>
											<small class="text-danger">
												<i class="fas fa-exclamation-circle me-1"></i>
												{{ invoice.days_overdue }} {{ _('days overdue') }}
											</small>
										</div>
									{% else %}
										<div class="due-date">
											<div class="date-value">{{ invoice.due_date.strftime('%b %d, %Y') }}</div>
											<small class="text-muted">{{ invoice.due_date.strftime('%Y-%m-%d') }}</small>
										</div>
									{% endif %}
								</td>
								<td class="align-middle">
									<div class="amount-info">
										<div class="amount-value">{{ "%.2f"|format(invoice.total_amount) }} {{ currency }}</div>
									</div>
								</td>
								<td class="align-middle">
									{% set status_config = {
										'draft': {'color': 'secondary', 'icon': 'edit', 'bg': 'bg-secondary', 'label': _('Draft')},
										'sent': {'color': 'info', 'icon': 'paper-plane', 'bg': 'bg-info', 'label': _('Sent')},
										'paid': {'color': 'success', 'icon': 'check-circle', 'bg': 'bg-success', 'label': _('Paid')},
										'overdue': {'color': 'danger', 'icon': 'exclamation-triangle', 'bg': 'bg-danger', 'label': _('Overdue')},
										'cancelled': {'color': 'dark', 'icon': 'times-circle', 'bg': 'bg-dark', 'label': _('Cancelled')}
									} %}
									{% set config = status_config.get(invoice.status, status_config.draft) %}
									<span class="status-badge {{ config.bg }} text-white">
										<i class="fas fa-{{ config.icon }} me-1"></i>
										{{ config.label }}
									</span>
								</td>
								<td class="align-middle">
									<div class="payment-status-info">
										{% if invoice.payment_status == 'unpaid' %}
											<span class="payment-badge bg-danger text-white">
												<i class="fas fa-times-circle me-1"></i>{{ _('Unpaid') }}
											</span>
										{% elif invoice.payment_status == 'partially_paid' %}
											<span class="payment-badge bg-warning text-white">
												<i class="fas fa-clock me-1"></i>{{ _('Partial') }}
											</span>
											<div class="payment-progress mt-1">
												<div class="progress" style="height: 4px;">
													<div class="progress-bar bg-warning" 
														 style="width: {{ invoice.payment_percentage }}%"></div>
												</div>
												<small class="text-muted">{{ "%.0f"|format(invoice.payment_percentage) }}%</small>
											</div>
										{% elif invoice.payment_status == 'fully_paid' %}
											<span class="payment-badge bg-success text-white">
												<i class="fas fa-check-circle me-1"></i>{{ _('Paid') }}
											</span>
											{% if invoice.payment_date %}
											<div class="payment-date">
												<small class="text-muted">{{ invoice.payment_date.strftime('%b %d') }}</small>
											</div>
											{% endif %}
										{% elif invoice.payment_status == 'overpaid' %}
											<span class="payment-badge bg-info text-white">
												<i class="fas fa-plus-circle me-1"></i>{{ _('Overpaid') }}
											</span>
										{% endif %}
									</div>
								</td>
								<td class="align-middle text-center">
									<div class="btn-group btn-group-sm" role="group">
										<a href="{{ url_for('invoices.view_invoice', invoice_id=invoice.id) }}" 
										   class="btn btn-sm btn-action btn-action--view" 
										   title="{{ _('View Invoice') }}">
											<i class="fas fa-eye"></i>
										</a>
										<a href="{{ url_for('invoices.edit_invoice', invoice_id=invoice.id) }}" 
										   class="btn btn-sm btn-action btn-action--edit" 
										   title="{{ _('Edit Invoice') }}">
											<i class="fas fa-edit"></i>
										</a>
										<button type="button" 
										        class="btn btn-sm btn-action btn-action--more dropdown-toggle dropdown-toggle-split" 
										        data-bs-toggle="dropdown" 
										        aria-expanded="false">
											<span class="visually-hidden">{{ _('More actions') }}</span>
										</button>
										<ul class="dropdown-menu dropdown-menu-end" data-bs-auto-close="true">
											<li>
												<a class="dropdown-item" 
												   href="{{ url_for('invoices.export_invoice_csv', invoice_id=invoice.id) }}">
													<i class="fas fa-download me-2"></i> {{ _('Export CSV') }}
													</a>
											</li>
											<li>
												<a class="dropdown-item" 
												   href="{{ url_for('invoices.duplicate_invoice', invoice_id=invoice.id) }}">
													<i class="fas fa-copy me-2"></i> {{ _('Duplicate') }}
													</a>
											</li>
											<li>
												<a class="dropdown-item" 
												   href="{{ url_for('invoices.generate_from_time', invoice_id=invoice.id) }}">
													<i class="fas fa-clock me-2"></i> {{ _('Generate from Time') }}
													</a>
											</li>
											{% if invoice.payment_status != 'fully_paid' %}
											<li>
												<a class="dropdown-item text-success" 
												   href="{{ url_for('invoices.record_payment', invoice_id=invoice.id) }}">
													<i class="fas fa-money-bill-wave me-2"></i> {{ _('Record Payment') }}
												</a>
											</li>
											{% endif %}
											<li><hr class="dropdown-divider"></li>
											<li>
												<form method="POST" 
												      action="{{ url_for('invoices.delete_invoice', invoice_id=invoice.id) }}" 
												      class="d-inline"
												      data-confirm="{{ _('Are you sure you want to delete this invoice? This action cannot be undone.') }}">
													<button type="submit" class="dropdown-item text-danger">
														<i class="fas fa-trash me-2"></i> {{ _('Delete') }}
														</button>
													</form>
												</li>
										</ul>
									</div>
								</td>
							</tr>
							{% endfor %}
						</tbody>
					</table>
				</div>
			{% else %}
				<div class="text-center py-5">
					<div class="empty-state">
						<i class="fas fa-file-invoice fa-3x text-muted mb-3"></i>
						<h5 class="text-muted">{{ _('No invoices found') }}</h5>
						<p class="text-muted mb-4">{{ _('Create your first invoice to get started with billing.') }}</p>
						<a href="{{ url_for('invoices.create_invoice') }}" class="btn btn-primary btn-lg">
							<i class="fas fa-plus me-2"></i> {{ _('Create Your First Invoice') }}
						</a>
					</div>
				</div>
			{% endif %}
		</div>
	</div>
</div>

<!-- Modern styling now handled by global CSS in base.css -->
<style>
/* Keep dropdown stacking sane; rely on global dropdown styles for look/feel */
.summary-card {
    transition: all 0.3s ease;
    border-radius: 12px;
}

.summary-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}

.summary-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
}

.summary-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 4px;
}

.summary-value {
    font-size: 20px;
    font-weight: 700;
    color: var(--text-primary);
}

/* Force table containers to allow overflow for dropdowns */
.table-responsive {
    overflow: visible !important;
    position: relative !important;
}

.card-body {
    overflow: visible !important;
}

/* Ensure dropdown menus work properly with maximum z-index */
.dropdown-menu {
    z-index: 9999 !important;
    min-width: 160px;
    position: absolute !important;
    transform: none !important;
}

/* Ensure dropdowns in table cells stack above ALL other content */
.table .dropdown {
    position: relative !important;
    z-index: 9998 !important;
}

.table .dropdown.show {
    z-index: 9999 !important;
}

.table .dropdown-menu {
    z-index: 9999 !important;
    position: absolute !important;
    top: 100% !important;
    left: auto !important;
    right: 0 !important;
    transform: none !important;
    margin-top: 0.25rem !important;
}

/* Ensure table and its containers don't clip dropdowns */
.table {
    overflow: visible !important;
    position: relative !important;
}

.table tbody tr {
    position: relative !important;
    z-index: 1 !important;
}

.table tbody tr:hover {
    z-index: 2 !important;
}

/* Force dropdown visibility */
.btn-group .dropdown-menu.show,
.dropdown.show .dropdown-menu {
    display: block !important;
    visibility: visible !important;
    opacity: 1 !important;
}

.dropdown-toggle::after {
    display: none;
}

.btn-group .dropdown-toggle-split::after {
    display: inline-block;
    margin-left: 0.255em;
    vertical-align: 0.255em;
    content: "";
    border-top: 0.3em solid;
    border-right: 0.3em solid transparent;
    border-bottom: 0;
    border-left: 0.3em solid transparent;
}

.invoice-number-badge {
    background: var(--primary-color);
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-weight: 600;
    font-size: 14px;
}

.client-info .client-name {
    font-weight: 600;
    color: var(--text-primary);
}

.project-badge {
    background: var(--light-color);
    color: var(--text-secondary);
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
}

.date-info .date-value {
    font-weight: 600;
    color: var(--text-primary);
}

.due-date.overdue .date-value {
    font-weight: 700;
}

.amount-value {
    font-weight: 700;
    color: var(--text-primary);
    font-size: 16px;
}

.status-badge {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.payment-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.payment-status-info {
    min-width: 80px;
}

.payment-progress {
    width: 60px;
}

.payment-date {
    margin-top: 2px;
}

.btn-group .btn { border-radius: 0 !important; margin-right: 0 !important; }
.btn-group .btn:first-child { border-top-left-radius: 6px !important; border-bottom-left-radius: 6px !important; }
.btn-group .btn:last-child { border-top-right-radius: 6px !important; border-bottom-right-radius: 6px !important; }

.empty-state {
    padding: 2rem;
}

.empty-state i {
    opacity: 0.5;
}

@media (max-width: 768px) {
    .summary-card {
        margin-bottom: 1rem;
    }
    
    .table-responsive {
        font-size: 14px;
    }
    
    .btn-group .btn {
        padding: 0.375rem 0.5rem;
        font-size: 12px;
    }
    
    .invoice-number-badge {
        font-size: 12px;
        padding: 4px 8px;
    }
    
    .status-badge {
        font-size: 10px;
        padding: 4px 8px;
    }
}
</style>
{% endblock %}

{% block scripts %}
<script type="application/json" id="i18n-json-invoices-list">
{
    "search_invoices": {{ _('Search invoices:')|tojson }},
    "length_menu": {{ _('Show _MENU_ invoices per page')|tojson }},
    "info": {{ _('Showing _START_ to _END_ of _TOTAL_ invoices')|tojson }},
    "confirm_delete_prefix": {{ _('Are you sure you want to delete invoice')|tojson }},
    "confirm_delete_suffix": {{ _('This action cannot be undone.')|tojson }}
}
</script>
<script>
var i18nList = (function(){
    try { var el = document.getElementById('i18n-json-invoices-list'); return el ? JSON.parse(el.textContent) : {}; }
    catch(e) { return {}; }
})();
</script>
<script>
$(document).ready(function() {
    // Initialize DataTable with enhanced features
    const table = $('#invoicesTable').DataTable({
        order: [[3, 'desc']], // Sort by issue date descending
        pageLength: 25,
        language: {
            search: i18nList.search_invoices || 'Search invoices:',
            lengthMenu: i18nList.length_menu || 'Show _MENU_ invoices per page',
            info: i18nList.info || 'Showing _START_ to _END_ of _TOTAL_ invoices'
        },
        responsive: true,
        dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
             '<"row"<"col-sm-12"tr>>' +
             '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
        columnDefs: [
            { orderable: false, targets: -1 } // Disable sorting on actions column
        ]
    });
    
    // Custom search functionality
    $('#searchInput').on('keyup', function() {
        table.search(this.value).draw();
    });
    
    // Add row hover effects
    $('#invoicesTable tbody tr').hover(
        function() {
            $(this).addClass('table-active');
        },
        function() {
            $(this).removeClass('table-active');
        }
    );
});

// Filter by status
function filterByStatus(status) {
    const table = $('#invoicesTable').DataTable();
    
    if (status === 'all') {
        table.column(6).search('').draw();
    } else {
        table.column(6).search(status).draw();
    }
    
    // Update active filter button
    $('.dropdown-item').removeClass('active');
    $(`[onclick="filterByStatus('${status}')"]`).addClass('active');
}

// Enhanced confirmation for delete
function confirmDelete(invoiceNumber) {
    const prefix = i18nList.confirm_delete_prefix || 'Are you sure you want to delete invoice';
    const suffix = i18nList.confirm_delete_suffix || 'This action cannot be undone.';
    return confirm(`${prefix} ${invoiceNumber}? ${suffix}`);
}

// Quick status update (if implemented in backend)
function updateStatus(invoiceId, newStatus) {
    // This would typically make an AJAX call to update the status
    console.log(`Updating invoice ${invoiceId} to status: ${newStatus}`);
}

// Handle generic data-confirm forms to avoid inline JS Jinja
$(document).on('submit', 'form[data-confirm]', function(e) {
    const message = $(this).attr('data-confirm');
    if (!confirm(message)) {
        e.preventDefault();
        return false;
    }
});
</script>
{% endblock %}
