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

let currentPage = 0;
const pageSize = 50;
let isLoading = false;

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

const setDefaultDates = () => {
    const today = dayjs().format('YYYY-MM-DD');
    document.getElementById('fromDate').value = today;
    document.getElementById('toDate').value = today;
};

const setupEventListeners = () => {
    const eventMap = {
        'searchForm': { event: 'submit', handler: fetchData },
        'fromDate': { event: 'change', handler: validateDates },
        'toDate': { event: 'change', handler: validateDates }
    };
    addEvents(eventMap);
};

const validateDates = () => {
    const fromDate = document.getElementById('fromDate');
    const toDate = document.getElementById('toDate');
    if (fromDate.value && toDate.value && fromDate.value > toDate.value) {
        alert('시작일자는 종료일자보다 클 수 없습니다.');
        fromDate.value = toDate.value;
    }
};

const fetchData = () => {
    isLoading = false;
    currentPage = 0;
    document.getElementById('jobList').scrollTop = 0;
    document.querySelector('tbody').innerHTML = '';
    fetchDataAndRender();
}

const fetchDataAndRender = async () => {
    const fromDateValue = document.getElementById('fromDate').value;
    const toDateValue = document.getElementById('toDate').value;
    if (!fromDateValue || !toDateValue) {
        alert('시작일자와 종료일자를 모두 입력해주세요.');
        return;
    }

    if (isLoading) return;
    isLoading = true;

    const jobName = document.getElementById('jobName').value;
    const fromDate = dayjs(document.getElementById('fromDate').value).format('YYYY-MM-DDTHH:mm:ss');
    const toDate = dayjs(document.getElementById('toDate').value).endOf('day').format('YYYY-MM-DDTHH:mm:ss');
    const searchParams = { fromDate: fromDate, toDate: toDate, jobName: jobName, page: currentPage, size: pageSize };
    const jobHistories = await scheduleService.getJobHistory(searchParams);

    if (jobHistories.length > 0) {
        appendJobHistories(jobHistories);
        currentPage++;
        isLoading = false;
        document.getElementById('jobList').addEventListener('scroll', handleScroll);
    } else {
        document.getElementById('jobList').removeEventListener('scroll', handleScroll);
    }
};

const appendJobHistories = (jobHistories) => {
  jobHistories.forEach(history => {
      const row = document.createElement('tr');
      const startTime = dayjs(history.startTime);
      const endTime = dayjs(history.endTime);
      const executionTime = Math.abs(endTime.diff(startTime, 'millisecond'));
      row.innerHTML = `
          <td>${history.jobName}</td>
          <td>${formatDateTime(history.startTime)}</td>
          <td>${formatDateTime(history.endTime)}</td>
          <td>${executionTime} ms</td>
          <td>${history.status}</td>
      `;
      document.querySelector('tbody').appendChild(row);
  });
};

const handleScroll = () => {
    const tableBody = document.getElementById('jobList');
    if (tableBody.scrollTop + tableBody.clientHeight >= tableBody.scrollHeight) {
        fetchDataAndRender();
    }
};
