import { state }                                        from './state.js';
import { showLoading, hideLoading, setStatus, showToast } from './ui.js';
import { renderGrid }                                    from './grid.js';
import * as history                                      from './history.js';

const inputPrefix            = document.getElementById('input-prefix');
const inputDigits            = document.getElementById('input-digits');
const renameConflictModal    = document.getElementById('rename-conflict-modal');
const renameConflictCloseBtn = document.getElementById('rename-conflict-close');
const renameConflictList     = document.getElementById('rename-conflict-list');

renameConflictCloseBtn.addEventListener('click', () => {
  renameConflictModal.style.display = 'none';
});

export async function doRename() {
  if (!state.files.length || !state.currentFolder) return;
  const prefix = inputPrefix.value.trim() || 'photo';
  const digits = Math.max(1, Math.min(6, parseInt(inputDigits.value) || 3));

  const selectedArr   = [...state.selectedIdxs].sort((a, b) => a - b);
  const filesToRename = selectedArr.length > 0
    ? selectedArr.map(i => state.files[i]).filter(Boolean)
    : state.files;

  if (!filesToRename.length) return;

  // 선택된 파일이 있으면 변경될 이름이 미선택 파일 이름과 충돌하는지 확인
  if (selectedArr.length > 0) {
    const unselectedNames = new Set(
      state.files.filter((_, i) => !state.selectedIdxs.has(i)).map(f => f.name)
    );
    const newNames = filesToRename.map((f, i) => {
      const ext = f.name.split('.').pop().toLowerCase();
      return `${prefix}_${String(i + 1).padStart(digits, '0')}.${ext}`;
    });
    const conflicting = newNames.filter(n => unselectedNames.has(n));
    if (conflicting.length) {
      renameConflictList.replaceChildren(...conflicting.map(n => {
        const li = document.createElement('li');
        li.textContent = n;
        return li;
      }));
      renameConflictModal.style.display = 'flex';
      return;
    }
  }

  const examples = filesToRename.slice(0, 3).map((f, i) => {
    const ext = f.name.split('.').pop().toLowerCase();
    return `${f.name}  →  ${prefix}_${String(i + 1).padStart(digits, '0')}.${ext}`;
  }).join('\n');
  const more = filesToRename.length > 3 ? `\n... 외 ${filesToRename.length - 3}개` : '';

  if (!confirm(`📂 ${filesToRename.length}개 파일을 이름 변경합니다:\n\n${examples}${more}\n\n계속하시겠습니까?`)) return;

  showLoading('파일 이름 변경 중...');
  setStatus('이름 변경 중...', false);

  try {
    const result = await window.api.renameFiles({
      folderPath: state.currentFolder,
      files: filesToRename,
      prefix,
      digits,
    });
    hideLoading();
    if (result.errors.length) {
      alert('일부 오류:\n' + result.errors.join('\n'));
    } else {
      showToast(`✅ ${result.renamed.length}개 파일 이름 변경 완료!`);
      setStatus(`${result.renamed.length}개 파일 이름 변경 완료`, true);
    }
    const newList = await window.api.listImages(state.currentFolder);
    state.files.length = 0;
    state.files.push(...newList);
    state.selectedIdxs.clear();
    renderGrid();
    history.reset();
    history.push(state.files);
  } catch (e) {
    hideLoading();
    alert('오류 발생: ' + e.message);
  }
}
