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

{% block title %}{{ _('Salesman Email Mappings') }} - {{ _('Admin') }} - {{ app_name }}{% endblock %}

{% block content %}
{% set breadcrumbs = [
    {'text': 'Admin', 'url': url_for('admin.admin_dashboard')},
    {'text': 'Salesman Email Mappings'}
] %}

{{ page_header(
    icon_class='fas fa-envelope',
    title_text='Salesman Email Mappings',
    subtitle_text='Configure email addresses for salesman-based report distribution',
    breadcrumbs=breadcrumbs
) }}

<div class="bg-card-light dark:bg-card-dark p-6 rounded-xl border border-border-light dark:border-border-dark shadow-sm mb-6">
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 mb-4">
        <h3 class="text-lg font-semibold">{{ _('Email Mappings') }}</h3>
        <button onclick="openCreateModal()" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90">
            <i class="fas fa-plus mr-2"></i>{{ _('Add Mapping') }}
        </button>
    </div>

    <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-border-light dark:divide-border-dark enhanced-table responsive-cards">
            <thead class="bg-background-light dark:bg-background-dark">
                <tr>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        {{ _('Salesman Initial') }}
                    </th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        {{ _('Email Address') }}
                    </th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        {{ _('Pattern/Domain') }}
                    </th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        {{ _('Status') }}
                    </th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                        {{ _('Actions') }}
                    </th>
                </tr>
            </thead>
            <tbody id="mappingsTableBody" class="bg-white dark:bg-gray-900 divide-y divide-border-light dark:divide-border-dark">
                <tr>
                    <td colspan="5" class="px-6 py-4 text-center text-gray-500 dark:text-gray-400">
                        <i class="fas fa-spinner fa-spin mr-2"></i>{{ _('Loading...') }}
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- Create/Edit Modal -->
<div id="mappingModal" class="hidden fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4">
    <div class="bg-card-light dark:bg-card-dark rounded-lg shadow-xl p-6 max-w-md w-full">
        <div class="flex justify-between items-center mb-4">
            <h3 id="modalTitle" class="text-lg font-semibold">{{ _('Add Email Mapping') }}</h3>
            <button onclick="closeModal()" class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <form id="mappingForm" onsubmit="saveMapping(event)">
            <input type="hidden" id="mappingId">
            
            <div class="mb-4">
                <label for="salesmanInitial" class="form-label">
                    {{ _('Salesman Initial') }} <span class="text-red-500">*</span>
                </label>
                <input type="text" id="salesmanInitial" required 
                       class="form-input" placeholder="MM, PB, etc."
                       pattern="[A-Za-z]{1,20}" title="{{ _('1-20 letters only') }}">
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                    {{ _('The salesman initial from client custom fields (e.g., MM for Max Mustermann)') }}
                </p>
            </div>

            <div class="mb-4">
                <label class="form-label">
                    {{ _('Email Configuration') }}
                </label>
                <div class="space-y-3">
                    <div>
                        <label class="flex items-center cursor-pointer">
                            <input type="radio" name="emailType" value="direct" checked class="form-radio mr-2" onchange="updateEmailType()">
                            <span class="text-sm">{{ _('Direct Email Address') }}</span>
                        </label>
                        <input type="email" id="emailAddress" 
                               class="form-input mt-2" 
                               placeholder="salesman@example.com">
                    </div>
                    <div>
                        <label class="flex items-center cursor-pointer">
                            <input type="radio" name="emailType" value="pattern" class="form-radio mr-2" onchange="updateEmailType()">
                            <span class="text-sm">{{ _('Pattern (e.g., {value}@test.de)') }}</span>
                        </label>
                        <input type="text" id="emailPattern" 
                               class="form-input mt-2 hidden" 
                               placeholder="{value}@test.de">
                    </div>
                    <div>
                        <label class="flex items-center cursor-pointer">
                            <input type="radio" name="emailType" value="domain" class="form-radio mr-2" onchange="updateEmailType()">
                            <span class="text-sm">{{ _('Domain (e.g., test.de)') }}</span>
                        </label>
                        <input type="text" id="emailDomain" 
                               class="form-input mt-2 hidden" 
                               placeholder="test.de">
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                            {{ _('Will generate: {initial}@domain') }}
                        </p>
                    </div>
                </div>
            </div>

            <div class="mb-4">
                <label for="notes" class="form-label">
                    {{ _('Notes') }} ({{ _('optional') }})
                </label>
                <textarea id="notes" rows="2" class="form-input" 
                          placeholder="{{ _('Additional notes about this mapping') }}"></textarea>
            </div>

            <div class="mb-4">
                <label class="flex items-center cursor-pointer">
                    <input type="checkbox" id="isActive" checked class="form-checkbox mr-2">
                    <span class="text-sm text-gray-700 dark:text-gray-300">{{ _('Active') }}</span>
                </label>
            </div>

            <div id="emailPreview" class="mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg hidden">
                <p class="text-xs text-gray-600 dark:text-gray-400 mb-1">{{ _('Preview:') }}</p>
                <p class="font-mono text-sm" id="previewEmail"></p>
            </div>

            <div class="flex justify-end gap-4">
                <button type="button" onclick="closeModal()" 
                        class="px-4 py-2 border border-border-light dark:border-border-dark rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                    {{ _('Cancel') }}
                </button>
                <button type="submit" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90">
                    {{ _('Save') }}
                </button>
            </div>
        </form>
    </div>
</div>

<script>
let mappings = [];

// Load mappings on page load
document.addEventListener('DOMContentLoaded', function() {
    loadMappings();
    
    // Add preview on input change
    document.getElementById('salesmanInitial')?.addEventListener('input', updatePreview);
    document.getElementById('emailAddress')?.addEventListener('input', updatePreview);
    document.getElementById('emailPattern')?.addEventListener('input', updatePreview);
    document.getElementById('emailDomain')?.addEventListener('input', updatePreview);
});

function loadMappings() {
    fetch('{{ url_for("salesman_reports.get_email_mappings_api") }}')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                mappings = data.mappings;
                renderMappings();
            }
        })
        .catch(error => {
            console.error('Error loading mappings:', error);
            document.getElementById('mappingsTableBody').innerHTML = 
                '<tr><td colspan="5" class="px-6 py-4 text-center text-red-500">Error loading mappings</td></tr>';
        });
}

function renderMappings() {
    const tbody = document.getElementById('mappingsTableBody');
    
    if (mappings.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="5" class="px-6 py-4 text-center text-gray-500 dark:text-gray-400">
                    {{ _('No mappings configured. Click "Add Mapping" to create one.') }}
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = mappings.map(m => `
        <tr>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium mobile-card-header" data-label="{{ _('Salesman Initial') }}">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                    ${m.salesman_initial}
                </span>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm" data-label="{{ _('Email Address') }}">
                ${m.resolved_email || '<span class="text-gray-400">-</span>'}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400" data-label="{{ _('Pattern/Domain') }}">
                ${m.email_pattern || m.domain || m.email_address || '-'}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm" data-label="{{ _('Status') }}">
                ${m.is_active 
                    ? '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200">Active</span>'
                    : '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200">Inactive</span>'}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium mobile-actions" data-label="{{ _('Actions') }}">
                <button onclick="editMapping(${m.id})" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 mr-3">
                    <i class="fas fa-edit"></i>
                </button>
                <button onclick="deleteMapping(${m.id})" class="text-red-600 hover:text-red-900 dark:text-red-400">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    `).join('');
}

function openCreateModal() {
    document.getElementById('modalTitle').textContent = '{{ _("Add Email Mapping") }}';
    document.getElementById('mappingForm').reset();
    document.getElementById('mappingId').value = '';
    document.getElementById('isActive').checked = true;
    updateEmailType();
    document.getElementById('mappingModal').classList.remove('hidden');
}

function editMapping(id) {
    const mapping = mappings.find(m => m.id === id);
    if (!mapping) return;
    
    document.getElementById('modalTitle').textContent = '{{ _("Edit Email Mapping") }}';
    document.getElementById('mappingId').value = mapping.id;
    document.getElementById('salesmanInitial').value = mapping.salesman_initial;
    document.getElementById('notes').value = mapping.notes || '';
    document.getElementById('isActive').checked = mapping.is_active;
    
    // Set email type
    if (mapping.email_address) {
        document.querySelector('input[name="emailType"][value="direct"]').checked = true;
        document.getElementById('emailAddress').value = mapping.email_address;
    } else if (mapping.email_pattern) {
        document.querySelector('input[name="emailType"][value="pattern"]').checked = true;
        document.getElementById('emailPattern').value = mapping.email_pattern;
    } else if (mapping.domain) {
        document.querySelector('input[name="emailType"][value="domain"]').checked = true;
        document.getElementById('emailDomain').value = mapping.domain;
    }
    
    updateEmailType();
    updatePreview();
    document.getElementById('mappingModal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('mappingModal').classList.add('hidden');
    document.getElementById('mappingForm').reset();
}

function updateEmailType() {
    const emailType = document.querySelector('input[name="emailType"]:checked').value;
    
    document.getElementById('emailAddress').classList.add('hidden');
    document.getElementById('emailPattern').classList.add('hidden');
    document.getElementById('emailDomain').classList.add('hidden');
    
    if (emailType === 'direct') {
        document.getElementById('emailAddress').classList.remove('hidden');
        document.getElementById('emailAddress').required = true;
    } else if (emailType === 'pattern') {
        document.getElementById('emailPattern').classList.remove('hidden');
        document.getElementById('emailPattern').required = true;
    } else if (emailType === 'domain') {
        document.getElementById('emailDomain').classList.remove('hidden');
        document.getElementById('emailDomain').required = true;
    }
    
    updatePreview();
}

function updatePreview() {
    const initial = document.getElementById('salesmanInitial').value.toUpperCase();
    const emailType = document.querySelector('input[name="emailType"]:checked')?.value;
    const previewDiv = document.getElementById('emailPreview');
    const previewEmail = document.getElementById('previewEmail');
    
    if (!initial) {
        previewDiv.classList.add('hidden');
        return;
    }
    
    let email = '';
    if (emailType === 'direct') {
        email = document.getElementById('emailAddress').value;
    } else if (emailType === 'pattern') {
        const pattern = document.getElementById('emailPattern').value;
        email = pattern.replace('{value}', initial);
    } else if (emailType === 'domain') {
        const domain = document.getElementById('emailDomain').value;
        email = `${initial}@${domain}`;
    }
    
    if (email) {
        previewEmail.textContent = email;
        previewDiv.classList.remove('hidden');
    } else {
        previewDiv.classList.add('hidden');
    }
}

function saveMapping(event) {
    event.preventDefault();
    
    const id = document.getElementById('mappingId').value;
    const salesmanInitial = document.getElementById('salesmanInitial').value.toUpperCase().trim();
    const emailType = document.querySelector('input[name="emailType"]:checked').value;
    const isActive = document.getElementById('isActive').checked;
    const notes = document.getElementById('notes').value;
    
    const data = {
        salesman_initial: salesmanInitial,
        is_active: isActive,
        notes: notes
    };
    
    if (emailType === 'direct') {
        data.email_address = document.getElementById('emailAddress').value;
    } else if (emailType === 'pattern') {
        data.email_pattern = document.getElementById('emailPattern').value;
    } else if (emailType === 'domain') {
        data.domain = document.getElementById('emailDomain').value;
    }
    
    const url = id 
        ? `{{ url_for('salesman_reports.update_email_mapping', mapping_id=0) }}`.replace('0', id)
        : '{{ url_for("salesman_reports.create_email_mapping") }}';
    const method = id ? 'PUT' : 'POST';
    
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrfToken
        },
        credentials: 'same-origin',
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            closeModal();
            loadMappings();
        } else {
            alert(result.message || '{{ _("Error saving mapping") }}');
        }
    })
    .catch(error => {
        alert('{{ _("Error saving mapping") }}: ' + error.message);
    });
}

function deleteMapping(id) {
    if (!confirm('{{ _("Are you sure you want to delete this mapping?") }}')) {
        return;
    }
    
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '';
    const url = `{{ url_for('salesman_reports.delete_email_mapping', mapping_id=0) }}`.replace('0', id);
    
    fetch(url, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': csrfToken
        },
        credentials: 'same-origin'
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            loadMappings();
        } else {
            alert(result.message || '{{ _("Error deleting mapping") }}');
        }
    })
    .catch(error => {
        alert('{{ _("Error deleting mapping") }}: ' + error.message);
    });
}
</script>
{% endblock %}

