import { formatDateTime } from '../../common/common.js';
import scheduleService from '../../apis/schedule-api.js';

document.addEventListener('DOMContentLoaded', () => {
    fetchDataAndRender();
    setupEventListeners();
    manageTooltips.init();
});

const setupEventListeners = () => {
    document.getElementById('searchForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        fetchDataAndRender();
    });
    document.getElementById('refreshJobBtn').addEventListener('click', refreshJobs);
};

const fetchDataAndRender = async () => {
    const searchParams = new URLSearchParams(new FormData(document.getElementById('searchForm')));
    const jobs = await scheduleService.getAllJobs(searchParams);
    updateTable(jobs);
};

const refreshJobs = async () => {
    if (await scheduleService.refreshJob()) {
        alert('스케줄이 재적용 되었습니다.');
        manageTooltips.hideAll();
        fetchDataAndRender();
    }
};

const updateTable = (jobs) => {
    const tableBody = document.querySelector('tbody');
    tableBody.innerHTML = jobs.map(job => `
        <tr>
            <td>${job.group}</td>
            <td>${job.name}</td>
            <td>${job.cronExpression}</td>
            <td><span class="badge ${getStatusBadgeClass(job.status)}">${job.status}</span></td>
            <td>
                <button class="badge btn btn-sm btn-secondary detail-btn" data-group="${job.group}" data-name="${job.name}">
                    <i class="bi bi-eye"></i> 상세
                </button>
            </td>
        </tr>
    `).join('');

    document.querySelectorAll('.detail-btn').forEach(btn => btn.addEventListener('click', showJobDetail));
};

const showJobDetail = async ({ target }) => {
    const { group, name } = target.closest('button').dataset;
    const jobDetail = await scheduleService.getJobDetail(group, name);
    document.getElementById('scheduleDetailContent').innerHTML = createDetailContent(jobDetail);

    new bootstrap.Modal(document.getElementById('scheduleDetailModal')).show();
    updateJobControlButtons(jobDetail.status);
    setupDetailModalEventListeners(group, name);
};

const createDetailContent = (jobDetail) => `
    <div class="card">
        <ul class="list-group list-group-flush">
            ${createDetailItem('그룹', jobDetail.group, 'bi-people')}
            ${createDetailItem('잡 이름', jobDetail.name, 'bi-briefcase')}
            ${createDetailItem('설명', jobDetail.description || '-', 'bi-card-text')}
            ${createDetailItem('스케줄', `<input type="text" class="form-control form-control-sm" id="cronExpression" value="${jobDetail.cronExpression}">`, 'bi-calendar-event')}
            ${createDetailItem('다음 실행', formatDateTime(jobDetail.nextFireTime), 'bi-clock')}
            ${createDetailItem('이전 실행', formatDateTime(jobDetail.previousFireTime), 'bi-clock-history')}
            ${createDetailItem('상태', `<span class="badge ${getStatusBadgeClass(jobDetail.status)}">${jobDetail.status}</span>`, 'bi-activity')}
        </ul>
    </div>
`;

const createDetailItem = (label, value, iconClass) => `
    <li class="list-group-item">
        <div class="row align-items-center">
            <div class="col-4">
                <i class="bi ${iconClass} text-primary me-2"></i>
                <strong>${label}</strong>
            </div>
            <div class="col-8">${value}</div>
        </div>
    </li>
`;

const getStatusBadgeClass = (status) => {
    const statusClasses = {
        'NONE': 'bg-secondary',
        'NORMAL': 'bg-success',
        'PAUSED': 'bg-warning',
        'COMPLETE': 'bg-info',
        'ERROR': 'bg-danger',
        'BLOCKED': 'bg-dark'
    };
    return statusClasses[status] || 'bg-secondary';
};

const setupDetailModalEventListeners = (group, name) => {
    document.getElementById('pauseJobBtn').onclick = () => updateJobStatus(group, name, 'PAUSED', scheduleService.pauseJob);
    document.getElementById('resumeJobBtn').onclick = () => updateJobStatus(group, name, 'NORMAL', scheduleService.resumeJob);
    document.getElementById('updateCronBtn').onclick = () => updateCronExpression(group, name);
};

const updateCronExpression = async (group, name) => {
    const newCronExpression = document.getElementById('cronExpression').value;
    if (await scheduleService.rescheduleJob(group, name, newCronExpression)) {
        alert('스케쥴이 수정 되었습니다.');
        fetchDataAndRender();
    } else {
        alert('스케쥴 수정이 실패했습니다.');
    }
};

const updateJobControlButtons = (status) => {
    const updateButtonState = (button, isEnabled) => {
        button.disabled = !isEnabled;
        button.classList.toggle(button.dataset.enabledClass, isEnabled);
        button.classList.toggle('btn-outline-secondary', !isEnabled);
    };

    const [pauseJobBtn, resumeJobBtn] = ['pauseJobBtn', 'resumeJobBtn'].map(id => document.getElementById(id));
    const isPaused = status === 'PAUSED';
    const isActive = !['COMPLETE', 'ERROR'].includes(status);

    updateButtonState(pauseJobBtn, isActive && !isPaused);
    updateButtonState(resumeJobBtn, isPaused);
};

const updateJobStatus = async (group, name, newStatus, action) => {
    if (await action(group, name)) {
        const statusElement = document.querySelector('#scheduleDetailContent .badge');
        statusElement.className = `badge ${getStatusBadgeClass(newStatus)}`;
        statusElement.textContent = newStatus;

        updateJobControlButtons(newStatus);
        updateTableJobStatus(group, name, newStatus);
    }
};

const updateTableJobStatus = (group, name, newStatus) => {
    const tableRows = document.querySelectorAll('tbody tr');
    const targetRow = Array.from(tableRows).find(row => 
        row.cells[0].textContent === group && row.cells[1].textContent === name
    );
    if (targetRow) {
        targetRow.cells[3].innerHTML = `<span class="badge ${getStatusBadgeClass(newStatus)}">${newStatus}</span>`;
    }
};

const manageTooltips = {
    init: () => {
        document.querySelectorAll('[data-bs-toggle="tooltip"]')
            .forEach(el => new bootstrap.Tooltip(el));
    },
    hideAll: () => {
        const tooltip = bootstrap.Tooltip.getInstance('#refreshJobBtn');
        setTimeout(() => tooltip.hide(), 100);
    }
};