// /js/daily-issue-ui.js

const DOM = {
  dateSelect: document.getElementById('dateSelect'),
  projectSelect: document.getElementById('projectSelect'),
  issueTypeSelect: document.getElementById('issueTypeSelect'),
  timeStart: document.getElementById('timeStart'),
  timeEnd: document.getElementById('timeEnd'),
  workerList: document.getElementById('workerList'),
  form: document.getElementById('issueForm'),
  submitBtn: document.getElementById('submitBtn'),
};

function createOption(value, text) {
  const option = document.createElement('option');
  option.value = value;
  option.textContent = text;
  return option;
}

export function populateProjects(projects) {
  DOM.projectSelect.innerHTML = '<option value="">-- 프로젝트 선택 --</option>';
  if (Array.isArray(projects)) {
    projects.forEach(p => DOM.projectSelect.appendChild(createOption(p.project_id, p.project_name)));
  }
}

export function populateIssueTypes(issueTypes) {
  DOM.issueTypeSelect.innerHTML = '<option value="">-- 이슈 유형 선택 --</option>';
  if (Array.isArray(issueTypes)) {
    issueTypes.forEach(t => DOM.issueTypeSelect.appendChild(createOption(t.issue_type_id, `${t.category}:${t.subcategory}`)));
  }
}

export function populateTimeOptions() {
  for (let h = 0; h < 24; h++) {
    for (let m of [0, 30]) {
      const time = `${String(h).padStart(2, '0')}:${m === 0 ? '00' : '30'}`;
      DOM.timeStart.appendChild(createOption(time, time));
      DOM.timeEnd.appendChild(createOption(time, time.replace('00:00', '24:00')));
    }
  }
  DOM.timeEnd.value = "24:00"; // 기본값 설정
}

export function renderWorkerList(workers) {
  DOM.workerList.innerHTML = '';
  if (!Array.isArray(workers) || workers.length === 0) {
    DOM.workerList.textContent = '선택 가능한 작업자가 없습니다.';
    return;
  }
  workers.forEach(worker => {
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'btn';
    btn.textContent = worker.worker_name;
    btn.dataset.id = worker.user_id;
    btn.addEventListener('click', () => btn.classList.toggle('selected'));
    DOM.workerList.appendChild(btn);
  });
}

export function getFormData() {
  const selectedWorkers = [...DOM.workerList.querySelectorAll('.btn.selected')].map(b => b.dataset.id);

  if (selectedWorkers.length === 0) {
    alert('작업자를 한 명 이상 선택해주세요.');
    return null;
  }
  if (DOM.timeEnd.value <= DOM.timeStart.value) {
    alert('종료 시간은 시작 시간보다 이후여야 합니다.');
    return null;
  }
  
  const formData = new FormData(DOM.form);
  const data = {
    date: formData.get('dateSelect'), // input name 속성이 없어 직접 가져옴
    project_id: DOM.projectSelect.value,
    issue_type_id: DOM.issueTypeSelect.value,
    start_time: DOM.timeStart.value,
    end_time: DOM.timeEnd.value,
    user_ids: selectedWorkers, // user_id -> user_ids 로 명확하게 변경
  };

  for (const key in data) {
    if (!data[key] || (Array.isArray(data[key]) && data[key].length === 0)) {
        alert('모든 필수 항목을 입력해주세요.');
        return null;
    }
  }

  return data;
}

export function setSubmitButtonState(isLoading) {
    if (isLoading) {
        DOM.submitBtn.disabled = true;
        DOM.submitBtn.textContent = '등록 중...';
    } else {
        DOM.submitBtn.disabled = false;
        DOM.submitBtn.textContent = '등록';
    }
} 