// Contract Editor JavaScript
(function() {
    'use strict';
    
    let currentCustomer = null;
    let currentYear = 2024;
    let currentPassword = '';
    let originalPassword = '';
    let contractsData = {
        contracts: []
    };
    let originalData = null;

    const hourTypes = ['Mechanical', 'Software', 'Visit'];

    $(document).ready(function() {
        // Don't auto-initialize since this might be loaded as partial
    });

    function initializeEditor() {
        // Always reinitialize when called to handle navigation back to editor
        loadCustomers();
        setupEventListeners();
        
        // Check auth status
        if (window.SimpleAuth && window.SimpleAuth.token) {
            updateLoginStatus();
        }
        
        $(document).on('authStatusChanged', function() {
            updateLoginStatus();
        });
    }

    function updateLoginStatus() {
        const isAuthenticated = window.SimpleAuth && window.SimpleAuth.token;
        const loginLink = $('#login-link');
        
        if (isAuthenticated) {
            loginLink.text('Logout');
            loginLink.attr('onclick', 'SimpleAuth.logout(); return false;');
        } else {
            loginLink.text('Login');
            loginLink.attr('onclick', 'SimpleAuth.showLoginModal(); return false;');
        }
    }

    function loadCustomers() {
        $.ajax({
            url: '/api/auth/users',
            method: 'GET',
            success: function(users) {
                const select = $('#customer-select');
                select.empty();
                select.append('<option value="">-- Select Customer --</option>');
                
                users.forEach(function(user) {
                    select.append(`<option value="${user}">${user}</option>`);
                });
            },
            error: function(xhr) {
                console.error('Failed to load customers:', xhr);
                alert('Failed to load customer list. Please refresh the page.');
            }
        });
    }

    function setupEventListeners() {
        $('#customer-select').on('change', function() {
            if ($(this).val()) {
                loadContracts();
            } else {
                $('#contracts-container').hide();
                $('#password-editor').hide();
            }
        });
        
        $('#customer-password').on('input', function() {
            currentPassword = $(this).val();
            if (currentPassword !== originalPassword) {
                $('#password-status').text('Modified').css('color', '#ff6600');
            } else {
                $('#password-status').text('').css('color', '#666');
            }
        });
        
        $('#save-contracts-btn').on('click', saveContracts);
        $('#cancel-btn').on('click', cancelEditing);
        
        $(document).on('click', '.year-tab', function() {
            $('.year-tab').removeClass('active');
            $(this).addClass('active');
            currentYear = parseInt($(this).data('year'));
            renderContractsTable();
        });
        
        $('#add-year-btn').on('click', addYear);
        $('#delete-year-btn').on('click', deleteYear);
    }

    function loadContracts() {
        const customer = $('#customer-select').val();
        
        if (!customer) {
            alert('Please select a customer first.');
            return;
        }

        if (!window.SimpleAuth || !window.SimpleAuth.token) {
            alert('Please login first.');
            window.SimpleAuth.showLoginModal();
            return;
        }

        currentCustomer = customer;
        
        // Check if admin user
        const isAdmin = window.SimpleAuth && window.SimpleAuth.isAdmin && window.SimpleAuth.isAdmin();
        
        $.ajax({
            url: `/api/contracts/get?customer=${encodeURIComponent(customer)}&token=${encodeURIComponent(window.SimpleAuth.token)}`,
            method: 'GET',
            success: function(data) {
                contractsData = data;
                originalData = JSON.parse(JSON.stringify(data)); // Deep copy
                
                // Ensure all year/type combinations exist
                ensureAllCombinations();
                
                $('#selected-customer').text(customer);
                $('#contracts-container').show();
                
                // Regenerate year tabs from data
                regenerateYearTabs();
                
                renderContractsTable();
                
                // Load password if admin
                if (isAdmin) {
                    loadCustomerPassword(customer);
                }
            },
            error: function(xhr) {
                if (xhr.status === 401) {
                    alert('Please login first.');
                    window.SimpleAuth.showLoginModal();
                } else {
                    alert('Failed to load contracts. Error: ' + (xhr.responseJSON?.error || xhr.statusText));
                }
            }
        });
    }

    function ensureAllCombinations() {
        // Get all unique years from contracts
        const yearsInData = [...new Set(contractsData.contracts.map(c => c.Contract_Year))].sort((a, b) => a - b);
        const years = yearsInData.length > 0 ? yearsInData : [2024, 2025, 2026];
        
        years.forEach(year => {
            hourTypes.forEach(hourType => {
                const exists = contractsData.contracts.some(c => 
                    c.Contract_Year === year && c.Hour_Type === hourType
                );
                
                if (!exists) {
                    contractsData.contracts.push({
                        Contract_Year: year,
                        Hour_Type: hourType,
                        Contract_Hours: 0
                    });
                }
            });
        });
        
        // Sort by year desc, then by hour type
        contractsData.contracts.sort((a, b) => {
            if (b.Contract_Year !== a.Contract_Year) {
                return b.Contract_Year - a.Contract_Year;
            }
            return hourTypes.indexOf(a.Hour_Type) - hourTypes.indexOf(b.Hour_Type);
        });
    }

    function renderContractsTable() {
        const tbody = $('#contracts-tbody');
        tbody.empty();
        
        const yearContracts = contractsData.contracts.filter(c => c.Contract_Year === currentYear);
        
        yearContracts.forEach(contract => {
            const row = $('<tr>');
            
            row.append(`<td>${contract.Contract_Year}</td>`);
            row.append(`<td>${contract.Hour_Type}</td>`);
            row.append(`
                <td>
                    <input type="number" 
                           class="contract-hours-input" 
                           data-year="${contract.Contract_Year}" 
                           data-type="${contract.Hour_Type}"
                           value="${contract.Contract_Hours}" 
                           step="1"
                           min="0">
                </td>
            `);
            
            tbody.append(row);
        });
        
        // Attach change listeners
        $('.contract-hours-input').on('change', function() {
            const year = parseInt($(this).data('year'));
            const type = $(this).data('type');
            const value = parseFloat($(this).val()) || 0;
            
            updateContractValue(year, type, value);
        });
    }

    function updateContractValue(year, type, value) {
        const contract = contractsData.contracts.find(c => 
            c.Contract_Year === year && c.Hour_Type === type
        );
        
        if (contract) {
            contract.Contract_Hours = value;
        }
    }

    function loadCustomerPassword(customer) {
        $.ajax({
            url: `/api/auth/getPassword?customer=${encodeURIComponent(customer)}&token=${encodeURIComponent(window.SimpleAuth.token)}`,
            method: 'GET',
            success: function(data) {
                currentPassword = data.password || '';
                originalPassword = currentPassword;
                $('#customer-password').val(currentPassword);
                $('#password-editor').show();
                $('#password-status').text('').css('color', '#666');
            },
            error: function(xhr) {
                console.error('Failed to load password:', xhr);
                $('#password-editor').hide();
            }
        });
    }

    function saveContracts() {
        if (!currentCustomer) {
            alert('No customer selected.');
            return;
        }

        if (!window.SimpleAuth || !window.SimpleAuth.token) {
            alert('Please login first.');
            window.SimpleAuth.showLoginModal();
            return;
        }

        if (!confirm(`Save contract changes for ${currentCustomer}?`)) {
            return;
        }

        const isAdmin = window.SimpleAuth && window.SimpleAuth.isAdmin && window.SimpleAuth.isAdmin();
        const passwordChanged = isAdmin && (currentPassword !== originalPassword);

        // Debug logging
        console.log('Saving contracts for:', currentCustomer);
        console.log('contractsData:', contractsData);
        console.log('Number of contracts:', contractsData.contracts.length);

        // Save contracts
        $.ajax({
            url: `/api/contracts/save?customer=${encodeURIComponent(currentCustomer)}&token=${encodeURIComponent(window.SimpleAuth.token)}`,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(contractsData),
            success: function(response) {
                console.log('Save response:', response);
                originalData = JSON.parse(JSON.stringify(contractsData));
                
                // Save password if changed
                if (passwordChanged) {
                    saveCustomerPassword();
                } else {
                    alert('Contracts saved successfully!');
                }
            },
            error: function(xhr) {
                console.error('Save error:', xhr);
                if (xhr.status === 401) {
                    alert('Please login first.');
                    window.SimpleAuth.showLoginModal();
                } else {
                    alert('Failed to save contracts. Error: ' + (xhr.responseJSON?.error || xhr.statusText));
                }
            }
        });
    }

    function saveCustomerPassword() {
        $.ajax({
            url: `/api/auth/savePassword?customer=${encodeURIComponent(currentCustomer)}&token=${encodeURIComponent(window.SimpleAuth.token)}`,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ password: currentPassword }),
            success: function(response) {
                originalPassword = currentPassword;
                $('#password-status').text('Saved').css('color', '#00aa00');
                alert('Contracts and password saved successfully!');
            },
            error: function(xhr) {
                alert('Contracts saved, but failed to save password. Error: ' + (xhr.responseJSON?.error || xhr.statusText));
            }
        });
    }

    function cancelEditing() {
        if (!originalData) {
            $('#contracts-container').hide();
            $('#password-editor').hide();
            return;
        }

        const hasChanges = JSON.stringify(contractsData) !== JSON.stringify(originalData);
        const passwordChanged = currentPassword !== originalPassword;

        if (hasChanges || passwordChanged) {
            if (!confirm('Discard unsaved changes?')) {
                return;
            }
        }

        contractsData = JSON.parse(JSON.stringify(originalData));
        currentPassword = originalPassword;
        $('#customer-password').val(originalPassword);
        $('#password-status').text('').css('color', '#666');
        renderContractsTable();
    }

    function addYear() {
        // Get the latest year from contracts
        const maxYear = Math.max(...contractsData.contracts.map(c => c.Contract_Year));
        const newYear = maxYear + 1;
        
        // Add contracts for the new year
        hourTypes.forEach(hourType => {
            contractsData.contracts.push({
                Contract_Year: newYear,
                Hour_Type: hourType,
                Contract_Hours: 0
            });
        });
        
        // Sort contracts
        contractsData.contracts.sort((a, b) => {
            if (b.Contract_Year !== a.Contract_Year) {
                return b.Contract_Year - a.Contract_Year;
            }
            return hourTypes.indexOf(a.Hour_Type) - hourTypes.indexOf(b.Hour_Type);
        });
        
        // Add new year tab
        const newTab = $(`<button class="year-tab" data-year="${newYear}">${newYear}</button>`);
        newTab.on('click', function() {
            $('.year-tab').removeClass('active');
            $(this).addClass('active');
            currentYear = parseInt($(this).data('year'));
            renderContractsTable();
        });
        
        // Insert before the "Add Year" button
        newTab.insertBefore('#add-year-btn');
        
        // Switch to the new year
        $('.year-tab').removeClass('active');
        newTab.addClass('active');
        currentYear = newYear;
        renderContractsTable();
    }

    function regenerateYearTabs() {
        // Get all unique years from contracts data, sorted descending
        const years = [...new Set(contractsData.contracts.map(c => c.Contract_Year))].sort((a, b) => b - a);
        
        // Remove all existing year tabs (but keep the add button)
        $('.year-tab').remove();
        
        // Create tabs for each year
        years.forEach(year => {
            const tabButton = $(`<button class="year-tab" data-year="${year}">${year}</button>`);
            
            // Attach click handler
            tabButton.on('click', function() {
                $('.year-tab').removeClass('active');
                $(this).addClass('active');
                currentYear = parseInt($(this).data('year'));
                renderContractsTable();
            });
            
            // Insert before the "Add Year" button
            tabButton.insertBefore('#add-year-btn');
        });
        
        // Set the first year (highest) as active
        if (years.length > 0) {
            $('.year-tab').first().addClass('active');
            currentYear = years[0];
        }
    }

    function deleteYear() {
        if (!contractsData || contractsData.contracts.length === 0) {
            alert('No years to delete.');
            return;
        }

        // Get all unique years
        const years = [...new Set(contractsData.contracts.map(c => c.Contract_Year))].sort((a, b) => b - a);
        
        if (years.length === 1) {
            alert('You must keep at least one year.');
            return;
        }

        if (!confirm(`Delete all contracts for year ${currentYear}?`)) {
            return;
        }

        // Remove all contracts for current year
        contractsData.contracts = contractsData.contracts.filter(c => c.Contract_Year !== currentYear);

        // Remove the year tab
        $(`.year-tab[data-year="${currentYear}"]`).remove();

        // Switch to another year (the highest remaining year)
        const remainingYears = [...new Set(contractsData.contracts.map(c => c.Contract_Year))].sort((a, b) => b - a);
        
        if (remainingYears.length > 0) {
            const nextYear = remainingYears[0];
            currentYear = nextYear;
            
            // Set as active
            $(`.year-tab[data-year="${nextYear}"]`).addClass('active');
            renderContractsTable();
        }
    }

    // Export for testing and external initialization
    window.ContractEditor = {
        init: initializeEditor,
        loadContracts: loadContracts,
        saveContracts: saveContracts
    };

})();
