import { api } from '../../../js/api.js';
import { escapeHtml, showAlert, hideAlert } from '../../../js/utils.js';

export let allEducationForms = [];

export async function fetchEducationForms() {
    try {
        allEducationForms = await api.get('/api/education-forms');
        return allEducationForms;
    } catch (e) {
        console.error('Не удалось загрузить формы обучения');
        return [];
    }
}

export async function initEduForms() {
    const efTbody = document.getElementById('ef-tbody');
    const createEfForm = document.getElementById('create-ef-form');

    async function loadEF() {
        try {
            const forms = await fetchEducationForms();
            renderEfTable(forms);
        } catch (e) {
            efTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Ошибка загрузки</td></tr>';
        }
    }

    function renderEfTable(forms) {
        if (!forms || !forms.length) {
            efTbody.innerHTML = '<tr><td colspan="3" class="loading-row">Нет форм обучения</td></tr>';
            return;
        }
        efTbody.innerHTML = forms.map(ef => `
      <tr>
        <td>${ef.id}</td>
        <td>${escapeHtml(ef.name)}</td>
        <td><button class="btn btn-sm btn-danger btn-delete-edu-form" data-id="${ef.id}">Удалить</button></td>
      </tr>`).join('');
    }

    createEfForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        hideAlert('create-ef-alert');
        const name = document.getElementById('new-ef-name').value.trim();
        if (!name) { showAlert('create-ef-alert', 'Введите название', 'error'); return; }

        try {
            const data = await api.post('/api/education-forms', { name });
            showAlert('create-ef-alert', `Форма "${escapeHtml(data.name)}" создана`, 'success');
            createEfForm.reset();
            loadEF();
        } catch (e) {
            showAlert('create-ef-alert', e.message || 'Ошибка создания', 'error');
        }
    });

    efTbody.addEventListener('click', async (e) => {
        const btn = e.target.closest('.btn-delete-edu-form');
        if (!btn) return;
        if (!confirm('Удалить форму обучения?')) return;
        try {
            await api.delete('/api/education-forms/' + btn.dataset.id);
            loadEF();
        } catch (e) {
            alert(e.message || 'Ошибка удаления');
        }
    });

    loadEF();
}
