{% 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 btn-outline-light btn-sm">
				<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 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'},
										'sent': {'color': 'info', 'icon': 'paper-plane', 'bg': 'bg-info'},
										'paid': {'color': 'success', 'icon': 'check-circle', 'bg': 'bg-success'},
										'overdue': {'color': 'danger', 'icon': 'exclamation-triangle', 'bg': 'bg-danger'},
										'cancelled': {'color': 'dark', 'icon': 'times-circle', 'bg': 'bg-dark'}
									} %}
									{% 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>
										{{ invoice.status|title }}
									</span>
								</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>
										<div class="btn-group" role="group">
											<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">
												<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>
												<li><hr class="dropdown-divider"></li>
												<li>
													<form method="POST" 
													      action="{{ url_for('invoices.delete_invoice', invoice_id=invoice.id) }}" 
													      class="d-inline"
													      onsubmit="return 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>
									</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>

<style>
.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);
}

.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;
}

.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>
$(document).ready(function() {
    // Initialize DataTable with enhanced features
    const table = $('#invoicesTable').DataTable({
        order: [[3, 'desc']], // Sort by issue date descending
        pageLength: 25,
        language: {
            search: "Search invoices:",
            lengthMenu: "Show _MENU_ invoices per page",
            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) {
    return confirm(`Are you sure you want to delete invoice ${invoiceNumber}? This action cannot be undone.`);
}

// 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}`);
}
</script>
{% endblock %}
