let WorkshopManager = {
    _referenceData: {},
    _saving: false,
    _refsPromise: null,

    init: function () {
        this.bindEvents();
        this.loadSummary();
        this.loadWorkHistory();
        this.loadWorkshopList();
    },

    bindEvents: function () {
        $('#btnAddVehicle').on('click', () => { this.populateWorkshopModal(); $('#workshopModal').modal('show'); });
        $('#btnRefreshJobs').on('click', () => { this.loadSummary(); this.loadWorkHistory(); });
        $('#btnAddNewWorkshop').on('click', () => { this.populateWorkshopEditModal(); $('#workshopEditModal').modal('show'); });
        $('#btnSaveWorkshopDir').on('click', () => { this.saveWorkshopDir(); });
        $('#btnSaveWorkshop').on('click', () => { this.saveWorkshopEntry(); });
        $('#workshopSearch').on('input', debounce(() => { this.loadWorkHistory(); }, 300));
        $('#workshopFilter, #workshopStageFilter').on('change', () => { this.loadWorkHistory(); });
        $('#workshopSelect').on('change', (e) => { this.onWorkshopChange(e); });

        $(document).on('click', '.btn-edit-workshop', (e) => {
            this.populateWorkshopEditModal($(e.currentTarget).data('id'));
        });
        $(document).on('click', '.btn-view-job', (e) => {
            const id = $(e.currentTarget).data('id');
            if (id) window.location.href = 'maintenance.php?job_id=' + encodeURIComponent(id);
        });

        $('#workshopEditModal').on('hidden.bs.modal', () => { $('#workshopEditForm')[0]?.reset(); });
        $('#workshopModal').on('hidden.bs.modal', () => {
            $('#workshopModalAlert').addClass('d-none').find('.alert-content').empty();
        });
    },

    showModalAlert: function (msg, type) {
        const el = $('#workshopModalAlert');
        if (!el.length) return;
        el.removeClass('d-none alert-danger alert-success').addClass('alert-' + (type || 'danger'))
            .find('.alert-content').html(msg);
    },

    hideModalAlert: function () {
        $('#workshopModalAlert').addClass('d-none').find('.alert-content').empty();
    },

    loadSummary: function () {
        $.get('api/maintenance.php?action=jobs', function (res) {
            if (res.status !== 'success') return;
            const jobs = res.data || [];
            $('#kpiInWorkshop').text(jobs.filter(j => j.workflow_stage === 'Workshop In Progress').length);
            $('#kpiPendingService').text(jobs.filter(j => j.workflow_stage === 'Complaint Logged' || j.workflow_stage === 'Maintenance Review' || j.workflow_stage === 'Work Order Raised').length);
            $('#kpiCompleted').text(jobs.filter(j => j.workflow_stage === 'Closed').length);
            $('#kpiAwaitingPayment').text(jobs.filter(j => j.requisition_status === 'Raised' || j.requisition_status === 'Approved' || j.workflow_stage === 'Payment Not Made').length);
        });
    },

    loadWorkHistory: function () {
        const tbody = $('#workHistoryTable');
        if (!tbody.length) return;
        const search = $('#workshopSearch').val() || '';
        const workshop = $('#workshopFilter').val() || '';
        const stage = $('#workshopStageFilter').val() || '';
        tbody.html('<tr><td colspan="8" class="text-center text-muted py-4">Loading work history...</td></tr>');
        $.get('api/maintenance.php', { action: 'jobs', search: search, workshop: workshop, status: stage }, (res) => {
            if (res.status === 'success') {
                const jobs = res.data || [];
                $('#jobCount').text(jobs.length + ' job' + (jobs.length !== 1 ? 's' : ''));
                tbody.html(jobs.length
                    ? jobs.map(j => this.renderJobRow(j)).join('')
                    : '<tr><td colspan="8" class="text-center text-muted py-4">No jobs found</td></tr>');
            } else {
                tbody.html('<tr><td colspan="8" class="text-center text-danger py-4">' + esc(res.message || 'Error') + '</td></tr>');
            }
        });
    },

    renderJobRow: function (j) {
        const title = j.complaint_title || j.nature_of_fault || '-';
        const received = j.workshop_received_date || j.complaint_date || '-';
        const completed = j.work_completed_date || '-';
        const amount = Number(j.approved_amount || j.vetted_amount || j.quote_amount || j.cost_of_repair || 0);
        const stageBadge = this.stageBadge(j.workflow_stage);
        return '<tr>' +
            '<td><div class="fw-semibold">' + esc(j.plate_number || '-') + '</div><div class="small text-muted">' + esc(j.vehicle_name || '') + '</div></td>' +
            '<td>' + esc(title) + '</td>' +
            '<td>' + esc(j.workshop || '-') + '</td>' +
            '<td>' + esc(received) + '</td>' +
            '<td>' + esc(completed) + '</td>' +
            '<td>' + stageBadge + '</td>' +
            '<td class="fw-semibold">' + (amount > 0 ? fmtCurr(amount) : '-') + '</td>' +
            '<td class="text-end"><button type="button" class="btn btn-sm btn-outline-primary btn-view-job" data-id="' + esc(String(j.id)) + '" title="Open Job"><i class="bi bi-arrow-up-right-square"></i></button></td>' +
            '</tr>';
    },

    stageBadge: function (stage) {
        const map = {
            'Closed': 'bg-success',
            'Work Order Raised': 'bg-primary',
            'Workshop In Progress': 'bg-warning text-dark',
            'Inspection': 'bg-info text-dark',
            'Internal Control': 'bg-secondary',
            'Payment Made': 'bg-success',
            'Payment Not Made': 'bg-danger',
            'Cancelled': 'bg-dark',
            'Requisition Raised': 'bg-info text-dark',
            'Requisition Approved': 'bg-primary',
            'Requisition Rejected': 'bg-danger'
        };
        const cls = map[stage] || 'bg-light text-dark border';
        return '<span class="badge ' + cls + '">' + esc(stage || 'Unknown') + '</span>';
    },

    loadWorkshopList: function () {
        $.get('api/workshop.php', { action: 'list', status: 'active' }, (res) => {
            if (res.status !== 'success') return;
            const sel = $('#workshopFilter');
            sel.find('option:not(:first)').remove();
            (res.data || []).forEach(function (w) {
                sel.append('<option value="' + esc(w.name) + '">' + esc(w.name) + '</option>');
            });
        });
    },

    populateWorkshopEditModal: function (id) {
        const self = this;
        $('#workshopEditTitle').text(id ? 'Edit Workshop' : 'Add Workshop');
        $('#editWorkshopId').val(id || '');

        const citySelect = $('#editCity');
        if (!citySelect.find('option[value!=""]').length) {
            $.get('api/workshop.php', { action: 'cities' }, (res) => {
                if (res.status === 'success') {
                    citySelect.find('option:not(:first)').remove();
                    (res.data || []).forEach((c) => {
                        citySelect.append('<option value="' + esc(c.name) + '">' + esc(c.name) + '</option>');
                    });
                    if (id) self.fillWorkshopForm(id);
                }
            });
        } else if (id) {
            this.fillWorkshopForm(id);
        }
        $('#workshopEditModal').modal('show');
    },

    fillWorkshopForm: function (id) {
        $.get('api/workshop.php', { action: 'get', id: id }, (res) => {
            if (res.status === 'success' && res.data.length) {
                const w = res.data[0];
                $('#editWorkshopName').val(w.name);
                $('#editContactPerson').val(w.contact_person || '');
                $('#editPhone').val(w.phone || '');
                $('#editEmail').val(w.email || '');
                $('#editAddress').val(w.address || '');
                $('#editCity').val(w.city || '');
                $('#editVendorType').val(w.vendor_type || 'Workshop');
                $('#editStatus').val(w.status);
                $('#editInactiveReason').val(w.inactive_reason || '');
            }
        });
    },

    saveWorkshopDir: function () {
        if (this._saving) return;
        this._saving = true;
        const btn = $('#btnSaveWorkshopDir').prop('disabled', true);
        const payload = {
            id: $('#editWorkshopId').val(),
            name: $('#editWorkshopName').val(),
            contact_person: $('#editContactPerson').val(),
            phone: $('#editPhone').val(),
            email: $('#editEmail').val(),
            address: $('#editAddress').val(),
            city: $('#editCity').val(),
            vendor_type: $('#editVendorType').val(),
            status: $('#editStatus').val(),
            inactive_reason: $('#editStatus').val() === 'inactive' ? $('#editInactiveReason').val() : ''
        };
        $.post('api/workshop.php?action=save', payload, (res) => {
            if (res.status === 'success') {
                $('#workshopEditModal').modal('hide');
                showToast('Workshop saved!');
            } else {
                this.showModalAlert(res.message || 'Save failed', 'danger');
            }
        }).always(() => { this._saving = false; btn.prop('disabled', false); });
    },

    loadReferenceData: function () {
        if (!this._refsPromise) {
            this._refsPromise = $.get('api/maintenance.php?action=reference_data', (res) => {
                if (res.status === 'success') this._referenceData = res.data;
            });
        }
        return this._refsPromise;
    },

    populateWorkshopModal: function () {
        this.loadReferenceData().done(() => {
            const ref = this._referenceData;
            $('#workshopModalTitle').text('Add Vehicle to Workshop');
            $('#workshopId').val('');
            $('#vehicleSelect').html('<option value="">Select Vehicle</option>' + (ref.vehicles || []).map(v => '<option value="' + v.id + '">' + esc(v.label) + '</option>').join(''));
            $('#technicianSelect').html('<option value="">Select Technician</option>' + (ref.users || []).map(u => '<option value="' + u.id + '">' + esc(u.label) + '</option>').join(''));
            const ws = (ref.workshops || []).map(w => '<option value="' + w.id + '" data-contact="' + esc(w.contact_person || '') + '" data-phone="' + esc(w.phone || '') + '" data-email="' + esc(w.email || '') + '">' + esc(w.label) + '</option>').join('');
            $('#workshopSelect').html('<option value="">Select Workshop</option>' + ws);
            $('#workshopContactInfo').text('');
            $('#issueType').val('');
            $('#description').val('');
            $('#priority').val('medium');
            $('#estimatedDays').val(1);
            $('#startDate').val(new Date().toISOString().split('T')[0]);
        });
    },

    onWorkshopChange: function (e) {
        const opt = e.target.options[e.target.selectedIndex];
        const parts = [opt.dataset.contact, opt.dataset.phone, opt.dataset.email].filter(Boolean);
        $('#workshopContactInfo').text(parts.join(' | '));
    },

    saveWorkshopEntry: function () {
        if (this._saving) return;
        const vehicleId = parseInt($('#vehicleSelect').val());
        if (!vehicleId) { this.showModalAlert('Please select a vehicle', 'danger'); return; }
        this._saving = true;
        const btn = $('#btnSaveWorkshop').prop('disabled', true);
        this.hideModalAlert();
        const wsSelect = document.getElementById('workshopSelect');
        const wsName = wsSelect.options[wsSelect.selectedIndex]?.text || 'Main Workshop';
        const payload = {
            vehicle_id: vehicleId,
            driver_id: $('#technicianSelect').val() || null,
            complaint_title: 'Workshop: ' + $('#issueType').val(),
            nature_of_fault: $('#description').val(),
            workshop: wsName,
            workflow_stage: 'Work Order Raised',
            status: 'Pending',
            expected_completion_date: this.calcCompletion($('#startDate').val(), $('#estimatedDays').val())
        };
        $.post('api/maintenance.php?action=save_job', payload, (res) => {
            if (res.status === 'success') {
                $('#workshopModal').modal('hide');
                this.loadSummary();
                this.loadWorkHistory();
                showToast('Vehicle added to workshop successfully!');
            } else {
                this.showModalAlert(res.message || 'Save failed', 'danger');
            }
        }).always(() => { this._saving = false; btn.prop('disabled', false); });
    },

    calcCompletion: function (start, days) {
        const d = new Date(start);
        d.setDate(d.getDate() + parseInt(days));
        return d.toISOString().split('T')[0];
    }
};

function esc(text) {
    const d = document.createElement('div');
    d.textContent = text == null ? '' : String(text);
    return d.innerHTML;
}

function fmtCurr(v) {
    const n = Number(v || 0);
    return Number.isFinite(n) && n > 0 ? '₦' + Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '-';
}

function debounce(fn, wait) {
    let t;
    return function (...a) { clearTimeout(t); t = setTimeout(() => fn(...a), wait); };
}

function showToast(msg) {
    const el = document.createElement('div');
    el.className = 'position-fixed top-0 end-0 p-3';
    el.style.cssText = 'z-index:1100';
    el.innerHTML = '<div class="alert alert-success alert-dismissible fade show" role="alert">' + msg + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 5000);
}

$(function () {
    WorkshopManager.init();
    $('#btnExportWorkshopCsv').on('click', function () { window.location.href = 'api/data_export.php?type=workshop&format=csv'; });
    $('#btnExportWorkshopXlsx').on('click', function () { window.location.href = 'api/data_export.php?type=workshop&format=xlsx'; });
    $('#btnExportWorkshopPdf').on('click', function () { window.location.href = 'api/data_export.php?type=workshop&format=pdf'; });
});
