/**
 * Vehicle Assignment Management Module
 * Handles assignment CRUD operations and UI interactions
 */

class VehicleAssignmentManager {
    constructor(vehicleId) {
        this.vehicleId = vehicleId;
        this.currentAssignment = null;
        this.editingAssignment = null;
        this.drivers = [];
        this.companies = [];
        this._driversPromise = null;
        this._companiesPromise = null;
        this._assignmentPromise = null;
        this._historyPromise = null;
        this._assignmentDataLoaded = false;
        this.init();
    }

    init() {
        this.bindEvents();
        // Eager load drivers/companies so modal opens instantly
        this.loadDrivers();
        this.loadCompanies();
        // Defer assignment list/history until tab is first shown
        $('#assignment-tab').one('shown.bs.tab', () => {
            this._assignmentDataLoaded = true;
            this.loadCurrentAssignment();
            this.loadAssignmentHistory();
        });
    }

    bindEvents() {
        // Edit assignment button
        $('#btnEditAssignment').on('click', () => this.editCurrentAssignment());

        // New assignment button
        $('#btnNewAssignment').on('click', () => this.newAssignment());

        // Clear modal alert on dismiss
        $('#assignmentModal').on('hidden.bs.modal', () => this.hideModalAlert());

        // Save assignment
        $('#btnSaveAssignment').on('click', () => this.saveAssignment());

        // Driver search
        $('#assignmentDriverSelect').on('change', (e) => this.onDriverChange(e.target.value));

        // Date validation
        $('#assignmentStartDate, #assignmentEndDate').on('change', () => this.validateDates());
    }

    displayCurrentAssignmentData(assignments) {
        const sorted = (assignments || []).sort(function (a, b) {
            return new Date(b.assignment_start) - new Date(a.assignment_start);
        });
        const current = sorted.find(function (a) {
            if (a.status !== 'active') return false;
            const end = a.assignment_end;
            if (!end) return true;
            return new Date(end) >= new Date();
        });
        if (current) {
            this.currentAssignment = current;
            this.displayCurrentAssignment(current);
        } else {
            this.currentAssignment = null;
            this.displayNoAssignment();
        }
    }

    async loadCurrentAssignment() {
        if (this._assignmentPromise) return this._assignmentPromise;
        this._assignmentPromise = this._fetchCurrentAssignment();
        return this._assignmentPromise;
    }

    async _fetchCurrentAssignment() {
        try {
            const response = await fetch(`api/assignments.php?action=list&vehicle_id=${this.vehicleId}`);
            const data = await response.json();

            if (data.status === 'success') {
                this.displayCurrentAssignmentData(data.data);
            }
        } catch (error) {
            console.error('Error loading current assignment:', error);
            this.showAlert('Error loading current assignment', 'danger');
        }
    }

    async loadAssignmentHistory() {
        if (this._historyPromise) return this._historyPromise;
        this._historyPromise = this._fetchAssignmentHistory();
        return this._historyPromise;
    }

    async _fetchAssignmentHistory() {
        try {
            const response = await fetch(`api/assignments.php?action=history&vehicle_id=${this.vehicleId}`);
            const data = await response.json();

            if (data.status === 'success') {
                this.displayAssignmentHistory(data.data);
            }
        } catch (error) {
            console.error('Error loading assignment history:', error);
            this.showAlert('Error loading assignment history', 'danger');
        }
    }

    async loadDrivers(search = '') {
        if (search === '') {
            if (this._driversPromise) return this._driversPromise;
            this._driversPromise = this._fetchDrivers();
            return this._driversPromise;
        }
        return this._fetchDrivers(search);
    }

    async _fetchDrivers(search = '') {
        try {
            const response = await fetch(`api/assignments.php?action=drivers&search=${encodeURIComponent(search)}`);
            const data = await response.json();

            if (data.status === 'success') {
                this.drivers = data.data;
                this.populateDriverSelect();
            }
        } catch (error) {
            console.error('Error loading drivers:', error);
        }
    }

    async loadCompanies() {
        if (this._companiesPromise) return this._companiesPromise;
        this._companiesPromise = this._fetchCompanies();
        return this._companiesPromise;
    }

    async _fetchCompanies() {
        try {
            const response = await fetch('api/assignments.php?action=companies');
            const data = await response.json();

            if (data.status === 'success') {
                this.companies = data.data;
                this.populateCompanySelect();
            }
        } catch (error) {
            console.error('Error loading companies:', error);
        }
    }

    populateDriverSelect() {
        const select = $('#assignmentDriverSelect');
        select.empty();
        select.append(new Option('Select Driver', ''));

        if (!this.drivers.length) {
            select.append(new Option('No active drivers found', ''));
            select.prop('disabled', true);
            return;
        }

        select.prop('disabled', false);
        this.drivers.forEach(driver => {
            const label = `${driver.full_name || 'Unknown Driver'}${driver.driver_code ? ` (${driver.driver_code})` : ''}`;
            select.append(new Option(label, driver.id));
        });
    }

    populateCompanySelect() {
        const select = $('#assignmentCompanySelect');
        select.empty();
        select.append(new Option('Select Company', ''));

        if (!this.companies.length) {
            select.append(new Option('No active companies found', ''));
            select.prop('disabled', true);
            return;
        }

        select.prop('disabled', false);
        this.companies.forEach(company => {
            const label = `${company.name}${company.code ? ` (${company.code})` : ''}`;
            select.append(new Option(label, company.id));
        });
    }

    displayCurrentAssignment(assignment) {
        $('#assignmentDriver').text(assignment.driver_name || 'Unknown Driver');
        $('#assignmentStart').text(this.formatDate(assignment.assignment_start));
        $('#assignmentEnd').text(assignment.assignment_end ? this.formatDate(assignment.assignment_end) : 'Ongoing');
        $('#assignmentStatus').text(this.formatStatus(assignment.status));
        $('#assignmentLeasedDays').text(assignment.leased_days != null ? assignment.leased_days + ' day(s)' : 'N/A');
    }

    displayNoAssignment() {
        $('#assignmentDriver').text('No active assignment');
        $('#assignmentStart').text('-');
        $('#assignmentEnd').text('-');
        $('#assignmentStatus').text('-');
        $('#assignmentLeasedDays').text('-');
    }

    displayAssignmentHistory(history) {
        const tbody = $('#assignmentHistoryTable');
        tbody.empty();

        if (history.length === 0) {
            tbody.append('<tr><td colspan="6" class="text-center text-muted">No assignment history found</td></tr>');
            return;
        }

        history.forEach(assignment => {
            const row = `
                <tr>
                    <td>${assignment.driver_name || 'Unknown Driver'}</td>
                    <td>${assignment.company_name || '-'}</td>
                    <td>${this.formatDate(assignment.assignment_start)}</td>
                    <td>${assignment.assignment_end ? this.formatDate(assignment.assignment_end) : 'Ongoing'}</td>
                    <td><span class="badge bg-${this.getStatusColor(assignment.status)}">${this.formatStatus(assignment.status)}</span></td>
                    <td>${assignment.duration_days || 'N/A'} days</td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    editCurrentAssignment() {
        if (!this.currentAssignment) {
            this.showAlert('No active assignment to edit', 'warning');
            return;
        }
        this.editingAssignment = this.currentAssignment;
        this.showModal();
    }

    newAssignment() {
        this.editingAssignment = null;
        this.resetAssignmentModal();
        this.showModal();
    }

    resetAssignmentModal() {
        $('#assignmentId').val('');
        $('#assignmentVehicleId').val(this.vehicleId);
        $('#assignmentDriverSelect').val('');
        $('#assignmentCompanySelect').val('');
        $('#assignmentStartDate').val('');
        $('#assignmentEndDate').val('');
        $('#assignmentStatusSelect').val('active');
        $('#assignmentLeasedDaysInput').val('');
    }

    applyEditingValues() {
        if (!this.editingAssignment) {
            $('#assignmentModalTitle').text('New Assignment');
            return;
        }
        $('#assignmentModalTitle').text('Edit Assignment');
        $('#assignmentId').val(this.editingAssignment.id);
        $('#assignmentVehicleId').val(this.vehicleId);
        $('#assignmentDriverSelect').val(this.editingAssignment.driver_id);
        $('#assignmentCompanySelect').val(this.editingAssignment.company_id || '');
        $('#assignmentStartDate').val(this.editingAssignment.assignment_start);
        $('#assignmentEndDate').val(this.editingAssignment.assignment_end || '');
        $('#assignmentStatusSelect').val(this.editingAssignment.status);
        $('#assignmentLeasedDaysInput').val(this.editingAssignment.leased_days ?? '');
        this.editingAssignment = null;
    }

    async saveAssignment() {
        const formData = new FormData();
        formData.append('assignment_id', $('#assignmentId').val());
        formData.append('vehicle_id', $('#assignmentVehicleId').val());
        formData.append('driver_id', $('#assignmentDriverSelect').val());
        formData.append('company_id', $('#assignmentCompanySelect').val());
        formData.append('start_date', $('#assignmentStartDate').val());
        formData.append('end_date', $('#assignmentEndDate').val());
        formData.append('status', $('#assignmentStatusSelect').val());
        const leasedDays = $('#assignmentLeasedDaysInput').val();
        if (leasedDays !== '') {
            formData.append('leased_days', leasedDays);
        }

        if (!formData.get('driver_id') || !formData.get('start_date')) {
            this.showAlert('Please fill in all required fields', 'warning');
            return;
        }

        try {
            const response = await fetch('api/assignments.php?action=save', {
                method: 'POST',
                body: formData
            });

            const data = await response.json();

            if (data.status === 'success') {
                $('#btnNewAssignment').focus();
                this.hideModal();
                this.showAlert('Assignment saved successfully', 'success');
                // Invalidate caches so next fetch gets fresh data
                this._assignmentPromise = null;
                this._historyPromise = null;
                if (data.assignment && data.history) {
                    this.displayCurrentAssignmentData(data.assignment);
                    this.displayAssignmentHistory(data.history);
                } else {
                    this.loadCurrentAssignment();
                    this.loadAssignmentHistory();
                }
            } else {
                this.showModalAlert(data.message || 'Error saving assignment');
            }
        } catch (error) {
            console.error('Error saving assignment:', error);
            this.showModalAlert('Error saving assignment');
        }
    }

    onDriverChange(driverId) {
        // Could display driver details here
    }

    validateDates() {
        const startDate = $('#assignmentStartDate').val();
        const endDate = $('#assignmentEndDate').val();

        if (startDate && endDate && startDate > endDate) {
            $('#assignmentEndDate')[0].setCustomValidity('End date must be after start date');
        } else {
            $('#assignmentEndDate')[0].setCustomValidity('');
        }
    }

    formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString();
    }

    showModalAlert(message, type = 'danger') {
        const alert = $('#assignmentModalAlert');
        alert.removeClass('alert-success alert-danger alert-warning alert-info d-none')
             .addClass(`alert-${type}`)
             .text(message);
    }

    hideModalAlert() {
        $('#assignmentModalAlert').addClass('d-none');
    }

    showModal() {
        this.hideModalAlert();
        const driverSelect = $('#assignmentDriverSelect');
        const companySelect = $('#assignmentCompanySelect');
        driverSelect.empty();
        companySelect.empty();
        driverSelect.append(new Option('Loading drivers...', ''));
        companySelect.append(new Option('Loading companies...', ''));
        driverSelect.prop('disabled', true);
        companySelect.prop('disabled', true);

        const afterPopulate = function () {
            this.populateDriverSelect();
            this.populateCompanySelect();
            this.applyEditingValues();
            const modalEl = document.getElementById('assignmentModal');
            const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
            modal.show();
            // Focus first form field after modal opens to avoid aria-hidden conflict
            modalEl.addEventListener('shown.bs.modal', function () {
                $('#assignmentDriverSelect').focus();
            }, { once: true });
        }.bind(this);

        const waitPromises = [];
        if (!this.drivers.length) {
            waitPromises.push(this.loadDrivers());
        }
        if (!this.companies.length) {
            waitPromises.push(this.loadCompanies());
        }

        if (waitPromises.length) {
            Promise.all(waitPromises).then(afterPopulate).catch(function () {
                driverSelect.empty();
                driverSelect.append(new Option('Error loading drivers', ''));
                companySelect.empty();
                companySelect.append(new Option('Error loading companies', ''));
                const modalEl = document.getElementById('assignmentModal');
                const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
                modal.show();
            });
        } else {
            afterPopulate();
        }
    }

    hideModal() {
        const modalEl = document.getElementById('assignmentModal');
        const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
        modal.hide();
    }

    formatStatus(status) {
        const statusMap = {
            'active': 'Active',
            'inactive': 'Inactive',
            'suspended': 'Suspended'
        };
        return statusMap[status] || status;
    }

    getStatusColor(status) {
        const colorMap = {
            'active': 'success',
            'inactive': 'secondary',
            'suspended': 'warning'
        };
        return colorMap[status] || 'secondary';
    }

    showAlert(message, type = 'info') {
        const alertBox = $('#alertBox');
        alertBox.removeClass('alert-success alert-danger alert-warning alert-info')
               .addClass(`alert-${type}`)
               .text(message)
               .removeClass('d-none');

        // Auto-hide after 5 seconds
        setTimeout(() => {
            alertBox.addClass('d-none');
        }, 5000);
    }
}

// Initialize when document is ready
$(document).ready(function() {
    if (typeof VEHICLE_ID !== 'undefined') {
        window.assignmentManager = new VehicleAssignmentManager(VEHICLE_ID);
    }
});