{% extends "base.html" %}

{% block title %}Create Invoice - TimeTracker{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <!-- Header with Progress Indicator -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div class="d-flex align-items-center">
                    <h1 class="h3 mb-0 me-3">
                        <i class="fas fa-plus text-primary"></i>
                        Create New Invoice
                    </h1>
                    <div class="progress" style="width: 200px; height: 8px;">
                        <div class="progress-bar" role="progressbar" style="width: 25%" id="progressBar"></div>
                    </div>
                </div>
                <a href="{{ url_for('invoices.list_invoices') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Invoices
                </a>
            </div>

            <!-- Step Indicator -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card shadow-sm">
                        <div class="card-body py-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="d-flex align-items-center step-indicator active" data-step="1">
                                    <div class="step-number">1</div>
                                    <span class="step-label ms-2">Basic Info</span>
                                </div>
                                <div class="step-line"></div>
                                <div class="d-flex align-items-center step-indicator" data-step="2">
                                    <div class="step-number">2</div>
                                    <span class="step-label ms-2">Client Details</span>
                                </div>
                                <div class="step-line"></div>
                                <div class="d-flex align-items-center step-indicator" data-step="3">
                                    <div class="step-number">3</div>
                                    <span class="step-label ms-2">Settings</span>
                                </div>
                                <div class="step-line"></div>
                                <div class="d-flex align-items-center step-indicator" data-step="4">
                                    <div class="step-number">4</div>
                                    <span class="step-label ms-2">Review</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <form method="POST" id="invoiceForm">
                <div class="row">
                    <div class="col-lg-8">
                        <!-- Step 1: Basic Information -->
                        <div class="card shadow step-card active" id="step1">
                            <div class="card-header py-3 bg-primary text-white">
                                <h6 class="m-0 font-weight-bold">
                                    <i class="fas fa-info-circle me-2"></i>Step 1: Basic Information
                                </h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-floating mb-3">
                                            <select class="form-select" id="project_id" name="project_id" required>
                                                <option value="">Select a project...</option>
                                                {% for project in projects %}
                                                <option value="{{ project.id }}" 
                                                        data-client="{{ project.client }}"
                                                        data-hourly-rate="{{ project.hourly_rate or 0 }}">
                                                    {{ project.name }} ({{ project.client }})
                                                </option>
                                                {% endfor %}
                                            </select>
                                            <label for="project_id">Project *</label>
                                            <div class="form-text">
                                                <i class="fas fa-lightbulb text-warning me-1"></i>
                                                Select the project this invoice is for
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-floating mb-3">
                                            <input type="date" class="form-control" id="due_date" name="due_date" 
                                                   value="{{ default_due_date }}" required>
                                            <label for="due_date">Due Date *</label>
                                            <div class="form-text">
                                                <i class="fas fa-calendar text-info me-1"></i>
                                                When payment is due
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="d-flex justify-content-end">
                                    <button type="button" class="btn btn-primary" onclick="nextStep()">
                                        Next: Client Details <i class="fas fa-arrow-right ms-1"></i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Step 2: Client Details -->
                        <div class="card shadow step-card" id="step2" style="display: none;">
                            <div class="card-header py-3 bg-info text-white">
                                <h6 class="m-0 font-weight-bold">
                                    <i class="fas fa-user me-2"></i>Step 2: Client Details
                                </h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-floating mb-3">
                                            <input type="text" class="form-control" id="client_name" name="client_name" 
                                                   placeholder="Client or company name" required>
                                            <label for="client_name">Client Name *</label>
                                            <div class="form-text">
                                                <i class="fas fa-building text-primary me-1"></i>
                                                Who to bill
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-floating mb-3">
                                            <input type="email" class="form-control" id="client_email" name="client_email" 
                                                   placeholder="client@example.com">
                                            <label for="client_email">Client Email</label>
                                            <div class="form-text">
                                                <i class="fas fa-envelope text-muted me-1"></i>
                                                Optional email for sending invoices
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-floating mb-3">
                                    <textarea class="form-control" id="client_address" name="client_address" 
                                              style="height: 100px" placeholder="Client billing address (optional)"></textarea>
                                    <label for="client_address">Client Address</label>
                                    <div class="form-text">
                                        <i class="fas fa-map-marker-alt text-muted me-1"></i>
                                        Optional billing address
                                    </div>
                                </div>
                                
                                <div class="d-flex justify-content-between">
                                    <button type="button" class="btn btn-outline-secondary" onclick="previousStep()">
                                        <i class="fas fa-arrow-left me-1"></i> Previous
                                    </button>
                                    <button type="button" class="btn btn-primary" onclick="nextStep()">
                                        Next: Settings <i class="fas fa-arrow-right ms-1"></i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Step 3: Settings -->
                        <div class="card shadow step-card" id="step3" style="display: none;">
                            <div class="card-header py-3 bg-warning text-dark">
                                <h6 class="m-0 font-weight-bold">
                                    <i class="fas fa-cog me-2"></i>Step 3: Settings
                                </h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-floating mb-3">
                                            <input type="number" class="form-control" id="tax_rate" name="tax_rate" 
                                                   value="0" min="0" max="100" step="0.01">
                                            <label for="tax_rate">Tax Rate (%)</label>
                                            <div class="form-text">
                                                <i class="fas fa-percentage text-success me-1"></i>
                                                Tax rate as percentage (e.g., 20 for 20%)
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-floating mb-3">
                                            <input type="text" class="form-control" id="currency" 
                                                   value="{{ settings.currency or 'EUR' }}" readonly>
                                            <label for="currency">Currency</label>
                                            <div class="form-text">
                                                <i class="fas fa-coins text-warning me-1"></i>
                                                System default currency
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-floating mb-3">
                                    <textarea class="form-control" id="notes" name="notes" 
                                              style="height: 100px" placeholder="Additional notes for the client"></textarea>
                                    <label for="notes">Notes</label>
                                    <div class="form-text">
                                        <i class="fas fa-sticky-note text-info me-1"></i>
                                        Optional notes to include on the invoice
                                    </div>
                                </div>

                                <div class="form-floating mb-3">
                                    <textarea class="form-control" id="terms" name="terms" 
                                              style="height: 100px" placeholder="Payment terms and conditions"></textarea>
                                    <label for="terms">Terms & Conditions</label>
                                    <div class="form-text">
                                        <i class="fas fa-file-contract text-primary me-1"></i>
                                        Payment terms and conditions
                                    </div>
                                </div>
                                
                                <div class="d-flex justify-content-between">
                                    <button type="button" class="btn btn-outline-secondary" onclick="previousStep()">
                                        <i class="fas fa-arrow-left me-1"></i> Previous
                                    </button>
                                    <button type="button" class="btn btn-primary" onclick="nextStep()">
                                        Next: Review <i class="fas fa-arrow-right ms-1"></i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Step 4: Review -->
                        <div class="card shadow step-card" id="step4" style="display: none;">
                            <div class="card-header py-3 bg-success text-white">
                                <h6 class="m-0 font-weight-bold">
                                    <i class="fas fa-check-circle me-2"></i>Step 4: Review & Create
                                </h6>
                            </div>
                            <div class="card-body">
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>Review your invoice details below before creating:</strong>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6 class="text-primary mb-3">Invoice Summary</h6>
                                        <div class="mb-2">
                                            <strong>Project:</strong> <span id="review-project">-</span>
                                        </div>
                                        <div class="mb-2">
                                            <strong>Client:</strong> <span id="review-client">-</span>
                                        </div>
                                        <div class="mb-2">
                                            <strong>Due Date:</strong> <span id="review-due-date">-</span>
                                        </div>
                                        <div class="mb-2">
                                            <strong>Tax Rate:</strong> <span id="review-tax">-</span>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <h6 class="text-primary mb-3">Additional Details</h6>
                                        <div class="mb-2">
                                            <strong>Notes:</strong> <span id="review-notes">-</span>
                                        </div>
                                        <div class="mb-2">
                                            <strong>Terms:</strong> <span id="review-terms">-</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="d-flex justify-content-between mt-4">
                                    <button type="button" class="btn btn-outline-secondary" onclick="previousStep()">
                                        <i class="fas fa-arrow-left me-1"></i> Previous
                                    </button>
                                    <button type="submit" class="btn btn-success btn-lg">
                                        <i class="fas fa-save me-2"></i>Create Invoice
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-4">
                        <!-- Project Information Card -->
                        <div class="card shadow mb-3">
                            <div class="card-header py-3 bg-light">
                                <h6 class="m-0 font-weight-bold text-primary">
                                    <i class="fas fa-project-diagram me-2"></i>Project Information
                                </h6>
                            </div>
                            <div class="card-body">
                                <div id="project-info" class="d-none">
                                    <div class="info-item mb-3">
                                        <div class="info-label">Client</div>
                                        <div class="info-value" id="project-client">-</div>
                                    </div>
                                    <div class="info-item mb-3">
                                        <div class="info-label">Hourly Rate</div>
                                        <div class="info-value" id="project-rate">{{ settings.currency or 'EUR' }}0.00</div>
                                    </div>
                                    <div class="info-item mb-3">
                                        <div class="info-label">Billable</div>
                                        <div class="info-value" id="project-billable">-</div>
                                    </div>
                                </div>
                                <div id="no-project-info" class="text-center text-muted py-3">
                                    <i class="fas fa-info-circle fa-2x mb-2"></i>
                                    <div>Select a project to see details</div>
                                </div>
                            </div>
                        </div>

                        <!-- Quick Tips Card -->
                        <div class="card shadow">
                            <div class="card-header py-3 bg-light">
                                <h6 class="m-0 font-weight-bold text-primary">
                                    <i class="fas fa-lightbulb me-2"></i>Quick Tips
                                </h6>
                            </div>
                            <div class="card-body">
                                <div class="tip-item mb-3">
                                    <div class="tip-icon text-warning">
                                        <i class="fas fa-clock"></i>
                                    </div>
                                    <div class="tip-content">
                                        <strong>Time Integration</strong>
                                        <p class="small text-muted mb-0">
                                            Generate line items from tracked time entries after creation
                                        </p>
                                    </div>
                                </div>
                                
                                <div class="tip-item mb-3">
                                    <div class="tip-icon text-success">
                                        <i class="fas fa-calculator"></i>
                                    </div>
                                    <div class="tip-content">
                                        <strong>Auto Calculations</strong>
                                        <p class="small text-muted mb-0">
                                            Tax and totals computed automatically
                                        </p>
                                    </div>
                                </div>
                                
                                <div class="tip-item">
                                    <div class="tip-icon text-primary">
                                        <i class="fas fa-file-export"></i>
                                    </div>
                                    <div class="tip-content">
                                        <strong>Export Options</strong>
                                        <p class="small text-muted mb-0">
                                            CSV export and PDF generation available
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
.step-indicator {
    display: flex;
    align-items: center;
    color: var(--text-muted);
    transition: all 0.3s ease;
}

.step-indicator.active {
    color: var(--primary-color);
}

.step-number {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: var(--light-color);
    border: 2px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.3s ease;
}

.step-indicator.active .step-number {
    background: var(--primary-color);
    border-color: var(--primary-color);
    color: white;
}

.step-line {
    flex: 1;
    height: 2px;
    background: var(--border-color);
    margin: 0 15px;
}

.step-indicator.active + .step-line {
    background: var(--primary-color);
}

.step-label {
    font-weight: 500;
    font-size: 14px;
}

.step-card {
    transition: all 0.3s ease;
    border: 2px solid transparent;
}

.step-card.active {
    border-color: var(--primary-color);
}

.info-item {
    padding: 12px;
    background: var(--light-color);
    border-radius: var(--border-radius-sm);
}

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

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

.tip-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
}

.tip-icon {
    font-size: 18px;
    margin-top: 2px;
}

.tip-content strong {
    display: block;
    font-size: 14px;
    margin-bottom: 4px;
}

.form-floating > .form-control:focus ~ label,
.form-floating > .form-control:not(:placeholder-shown) ~ label {
    color: var(--primary-color);
}

.form-control:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25);
}

@media (max-width: 768px) {
    .step-indicator .step-label {
        display: none;
    }
    
    .step-line {
        margin: 0 8px;
    }
    
    .progress {
        width: 150px !important;
    }
}
</style>
{% endblock %}

{% block extra_js %}
<script>
let currentStep = 1;
const totalSteps = 4;

document.addEventListener('DOMContentLoaded', function() {
    // Auto-fill client name when project is selected
    const projectSelect = document.getElementById('project_id');
    projectSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const clientName = selectedOption ? selectedOption.getAttribute('data-client') : '';
        const hourlyRate = selectedOption ? parseFloat(selectedOption.getAttribute('data-hourly-rate') || '0') : 0;

        const clientNameInput = document.getElementById('client_name');
        const projectInfo = document.getElementById('project-info');
        const noProjectInfo = document.getElementById('no-project-info');
        const projectClient = document.getElementById('project-client');
        const projectRate = document.getElementById('project-rate');
        const projectBillable = document.getElementById('project-billable');

        if (clientName) {
            clientNameInput.value = clientName;
            projectInfo.classList.remove('d-none');
            noProjectInfo.classList.add('d-none');
            projectClient.textContent = clientName;
            projectRate.textContent = '{{ settings.currency or "EUR" }}' + hourlyRate.toFixed(2);
            projectBillable.textContent = hourlyRate > 0 ? 'Yes' : 'No';
        } else {
            projectInfo.classList.add('d-none');
            noProjectInfo.classList.remove('d-none');
        }
    });

    // Set minimum due date to today
    const dueDate = document.getElementById('due_date');
    const today = new Date().toISOString().split('T')[0];
    dueDate.setAttribute('min', today);

    // Form validation
    const invoiceForm = document.getElementById('invoiceForm');
    invoiceForm.addEventListener('submit', function(e) {
        if (!validateForm()) {
            e.preventDefault();
            showAlert('Please fill in all required fields and complete all steps.', 'warning');
        }
    });
});

function nextStep() {
    if (validateCurrentStep()) {
        if (currentStep < totalSteps) {
            hideStep(currentStep);
            currentStep++;
            if (currentStep === 4) {
                updateReview();
            }
            showStep(currentStep);
            updateProgress();
            updateStepIndicators();
        }
    }
}

function previousStep() {
    if (currentStep > 1) {
        hideStep(currentStep);
        currentStep--;
        showStep(currentStep);
        updateProgress();
        updateStepIndicators();
    }
}

function showStep(step) {
    const card = document.getElementById(`step${step}`);
    if (card) {
        card.style.display = '';
        card.classList.add('active');
    }
}

function hideStep(step) {
    const card = document.getElementById(`step${step}`);
    if (card) {
        card.style.display = 'none';
        card.classList.remove('active');
    }
}

function updateProgress() {
    const progress = (currentStep / totalSteps) * 100;
    const bar = document.getElementById('progressBar');
    bar.style.width = progress + '%';
}

function updateStepIndicators() {
    document.querySelectorAll('.step-indicator').forEach(el => el.classList.remove('active'));
    const active = document.querySelector(`.step-indicator[data-step="${currentStep}"]`);
    if (active) active.classList.add('active');
}

function validateCurrentStep() {
    let isValid = true;
    const projectId = document.getElementById('project_id').value;
    const dueDate = document.getElementById('due_date').value;
    const clientName = document.getElementById('client_name').value;

    switch(currentStep) {
        case 1:
            if (!projectId || !dueDate) {
                isValid = false;
            }
            break;
        case 2:
            if (!clientName) {
                isValid = false;
            }
            break;
        case 3:
            // All fields are optional in step 3
            break;
    }

    if (!isValid) {
        showAlert('Please fill in all required fields before proceeding.', 'warning');
    }

    return isValid;
}

function validateForm() {
    return (
        document.getElementById('project_id').value &&
        document.getElementById('due_date').value &&
        document.getElementById('client_name').value
    );
}

function showAlert(message, type) {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    const container = document.querySelector('.container-fluid');
    if (container) {
        container.insertAdjacentHTML('afterbegin', alertHtml);
        // Auto-dismiss after 5 seconds
        setTimeout(() => {
            const alert = container.querySelector('.alert');
            if (alert) alert.remove();
        }, 5000);
    }
}

// Update review section when moving to step 4
function updateReview() {
    const projectSelect = document.getElementById('project_id');
    const projectText = projectSelect.options[projectSelect.selectedIndex]?.text || '-';
    document.getElementById('review-project').textContent = projectText;
    document.getElementById('review-client').textContent = document.getElementById('client_name').value || '-';
    document.getElementById('review-due-date').textContent = document.getElementById('due_date').value || '-';
    const tax = document.getElementById('tax_rate').value;
    document.getElementById('review-tax').textContent = tax ? `${tax}%` : '0%';
    document.getElementById('review-notes').textContent = document.getElementById('notes').value || 'None';
    document.getElementById('review-terms').textContent = document.getElementById('terms').value || 'None';
}
</script>
{% endblock %}
