{% extends "base.html" %}

{% block title %}Add Expense - Finance Tracker{% endblock %}

{% block content %}
<div class="form-container">
    <div class="glass-card form-card">
        <h1>💸 Add Expense to {{ category.name }}</h1>
        
        <form method="POST" enctype="multipart/form-data" class="form">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            
            <div class="form-group">
                <label for="description">Description *</label>
                <input type="text" id="description" name="description" required autofocus placeholder="e.g., Grocery shopping">
            </div>
            
            <div class="form-group">
                <label for="amount">Amount *</label>
                <input type="number" id="amount" name="amount" step="0.01" min="0.01" required placeholder="0.00">
            </div>
            
            <div class="form-group">
                <label for="date">Date *</label>
                <input type="date" id="date" name="date" value="{{ today }}" required>
            </div>
            
            <div class="form-group">
                <label for="paid_by">Paid By</label>
                <input type="text" id="paid_by" name="paid_by" placeholder="e.g., John, Cash, Credit Card">
            </div>
            
            <div class="form-group">
                <label for="tags">Tags</label>
                <input type="text" id="tags" name="tags" placeholder="Type or click tags below">
                
                {% if user_tags %}
                <div class="tag-suggestions">
                    {% for tag in user_tags %}
                    <button type="button" class="tag-btn" data-tag="{{ tag.name }}" style="background: {{ tag.color }}20; border: 1px solid {{ tag.color }}; color: {{ tag.color }};">
                        🏷️ {{ tag.name }}
                    </button>
                    {% endfor %}
                </div>
                <small>Click tags to add them. Multiple tags can be separated by commas.</small>
                {% else %}
                <small>No tags yet. <a href="{{ url_for('settings.create_tag') }}" style="color: #a5b4fc;">Create tags in Settings</a></small>
                {% endif %}
            </div>
            
            <div class="form-group">
                <label for="file">{{ _('expense.receipt') }}</label>
                <div class="receipt-upload-container">
                    <!-- Camera button for mobile -->
                    <button type="button" class="btn btn-camera" id="cameraBtn" onclick="openCamera()">
                        📸 {{ _('ocr.take_photo') }}
                    </button>
                    
                    <!-- File input -->
                    <input type="file" id="file" name="file" accept="image/*,.pdf" capture="environment">
                    
                    <!-- OCR processing indicator -->
                    <div id="ocrProcessing" class="ocr-processing" style="display: none;">
                        <div class="spinner"></div>
                        <span>{{ _('ocr.processing') }}</span>
                    </div>
                    
                    <!-- OCR results -->
                    <div id="ocrResults" class="ocr-results" style="display: none;"></div>
                </div>
                <small>{{ _('expense.receipt_hint') }} | 🤖 {{ _('ocr.ai_extraction') }}</small>
            </div>
            
            <div class="form-actions">
                <a href="{{ url_for('main.view_category', category_id=category.id) }}" class="btn btn-secondary">{{ _('common.cancel') }}</a>
                <button type="submit" class="btn btn-primary">💾 {{ _('expense.create') }}</button>
            </div>
        </form>
    </div>
</div>

<style>
.tag-suggestions {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-top: 0.75rem;
    margin-bottom: 0.5rem;
}

.tag-btn {
    padding: 0.5rem 1rem;
    border-radius: 8px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    background: rgba(255, 255, 255, 0.1);
}

.tag-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.tag-btn.active {
    opacity: 0.6;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const tagsInput = document.getElementById('tags');
    const tagButtons = document.querySelectorAll('.tag-btn');
    
    tagButtons.forEach(button => {
        button.addEventListener('click', function() {
            const tagName = this.getAttribute('data-tag');
            const currentTags = tagsInput.value;
            
            // Check if tag already exists
            const tagsArray = currentTags.split(',').map(t => t.trim()).filter(t => t);
            
            if (tagsArray.includes(tagName)) {
                // Remove tag
                const newTags = tagsArray.filter(t => t !== tagName);
                tagsInput.value = newTags.join(', ');
                this.classList.remove('active');
            } else {
                // Add tag
                if (currentTags.trim()) {
                    tagsInput.value = currentTags.trim() + ', ' + tagName;
                } else {
                    tagsInput.value = tagName;
                }
                this.classList.add('active');
            }
        });
    });
    
    // Update button states based on input
    tagsInput.addEventListener('input', function() {
        const tagsArray = this.value.split(',').map(t => t.trim()).filter(t => t);
        tagButtons.forEach(button => {
            const tagName = button.getAttribute('data-tag');
            if (tagsArray.includes(tagName)) {
                button.classList.add('active');
            } else {
                button.classList.remove('active');
            }
        });
    });
    
    // OCR functionality
    const fileInput = document.getElementById('file');
    const ocrProcessing = document.getElementById('ocrProcessing');
    const ocrResults = document.getElementById('ocrResults');
    const amountInput = document.getElementById('amount');
    const descriptionInput = document.getElementById('description');
    const dateInput = document.getElementById('date');
    
    if (fileInput) {
        fileInput.addEventListener('change', async function(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            // Only process images for OCR
            if (!file.type.startsWith('image/')) return;
            
            // Show processing indicator
            ocrProcessing.style.display = 'flex';
            ocrResults.style.display = 'none';
            
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                const response = await fetch('/api/ocr/process', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                ocrProcessing.style.display = 'none';
                
                if (data.success) {
                    displayOCRResults(data);
                } else {
                    ocrResults.innerHTML = `<div class="ocr-error">❌ ${data.error || 'OCR failed'}</div>`;
                    ocrResults.style.display = 'block';
                }
            } catch (error) {
                ocrProcessing.style.display = 'none';
                ocrResults.innerHTML = `<div class="ocr-error">❌ Error: ${error.message}</div>`;
                ocrResults.style.display = 'block';
            }
        });
    }
    
    function displayOCRResults(data) {
        const confidenceClass = data.confidence === 'high' ? 'success' : 
                               data.confidence === 'medium' ? 'warning' : 'low';
        
        let html = `<div class="ocr-result-box ${confidenceClass}">`;
        html += `<div class="ocr-header">🤖 AI Detected</div>`;
        
        if (data.amount) {
            html += `<div class="ocr-field">
                <strong>Amount:</strong> ${data.amount.toFixed(2)}
                <button type="button" class="btn-apply" onclick="applyOCRAmount(${data.amount})">Use This</button>
            </div>`;
        }
        
        if (data.merchant) {
            html += `<div class="ocr-field">
                <strong>Merchant:</strong> ${data.merchant}
                <button type="button" class="btn-apply" onclick="applyOCRMerchant('${escapeHtml(data.merchant)}')">Use This</button>
            </div>`;
        }
        
        if (data.date) {
            html += `<div class="ocr-field">
                <strong>Date:</strong> ${data.date}
                <button type="button" class="btn-apply" onclick="applyOCRDate('${data.date}')">Use This</button>
            </div>`;
        }
        
        const confidenceIcons = {
            'high': '✅',
            'medium': '⚠️',
            'low': '❌',
            'none': '❌'
        };
        
        html += `<div class="ocr-confidence">${confidenceIcons[data.confidence]} Confidence: ${data.confidence.toUpperCase()}</div>`;
        html += `</div>`;
        
        ocrResults.innerHTML = html;
        ocrResults.style.display = 'block';
    }
    
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
});

// Camera functionality
function openCamera() {
    const fileInput = document.getElementById('file');
    if (fileInput) fileInput.click();
}

// Apply OCR results
function applyOCRAmount(amount) {
    const input = document.getElementById('amount');
    if (input) {
        input.value = amount.toFixed(2);
        input.focus();
    }
}

function applyOCRMerchant(merchant) {
    const input = document.getElementById('description');
    if (input) {
        input.value = merchant;
        input.focus();
    }
}

function applyOCRDate(date) {
    const input = document.getElementById('date');
    if (input) {
        input.value = date;
        input.focus();
    }
}
</script>

<style>
/* Receipt upload styles */
.receipt-upload-container {
    margin-top: 0.5rem;
}

.btn-camera {
    display: block;
    width: 100%;
    margin-bottom: 0.5rem;
    padding: 0.75rem;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 0.9rem;
    cursor: pointer;
    transition: transform 0.2s;
}

.btn-camera:hover {
    transform: translateY(-2px);
}

.ocr-processing {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 8px;
    margin-top: 0.5rem;
}

.spinner {
    width: 20px;
    height: 20px;
    border: 3px solid rgba(255, 255, 255, 0.3);
    border-top-color: #fff;
    border-radius: 50%;
    animation: spin 0.6s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.ocr-results {
    margin-top: 0.5rem;
}

.ocr-result-box {
    padding: 1rem;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.ocr-result-box.success {
    border-color: rgba(34, 197, 94, 0.5);
    background: rgba(34, 197, 94, 0.1);
}

.ocr-result-box.warning {
    border-color: rgba(251, 191, 36, 0.5);
    background: rgba(251, 191, 36, 0.1);
}

.ocr-result-box.low {
    border-color: rgba(239, 68, 68, 0.5);
    background: rgba(239, 68, 68, 0.1);
}

.ocr-header {
    font-weight: 600;
    margin-bottom: 0.75rem;
    font-size: 0.95rem;
}

.ocr-field {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.5rem 0;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.ocr-field:last-of-type {
    border-bottom: none;
}

.btn-apply {
    padding: 0.25rem 0.75rem;
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 4px;
    color: #fff;
    font-size: 0.75rem;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-apply:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: translateY(-1px);
}

.ocr-confidence {
    margin-top: 0.75rem;
    padding-top: 0.75rem;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    font-size: 0.85rem;
    text-align: center;
}

.ocr-error {
    padding: 0.75rem;
    background: rgba(239, 68, 68, 0.1);
    border: 1px solid rgba(239, 68, 68, 0.5);
    border-radius: 8px;
    color: #fca5a5;
}

/* Mobile optimization */
@media (max-width: 768px) {
    .btn-camera {
        font-size: 1rem;
        padding: 1rem;
    }
    
    .ocr-field {
        flex-direction: column;
        align-items: flex-start;
        gap: 0.5rem;
    }
    
    .btn-apply {
        width: 100%;
        text-align: center;
    }
}
</style>
{% endblock %}
