const folderBtn = document.getElementById('folderBtn');
const zipBtn = document.getElementById('zipBtn');
const dropZone = document.getElementById('dropZone');
const output = document.getElementById('output');
const destinationInput = document.getElementById('destinationInput');
const browseDestinationBtn = document.getElementById('browseDestinationBtn');
const saveDestinationBtn = document.getElementById('saveDestinationBtn');
const openUnroutedBtn = document.getElementById('openUnroutedBtn');
const openDuplicatesBtn = document.getElementById('openDuplicatesBtn');
const openSkippedBtn = document.getElementById('openSkippedBtn');
const destinationStatus = document.getElementById('destinationStatus');
const previewOverlay = document.getElementById('previewOverlay');
const closePreviewBtn = document.getElementById('closePreviewBtn');
const clearPreviewBtn = document.getElementById('clearPreviewBtn');
const previewTitle = document.getElementById('previewTitle');
const previewMeta = document.getElementById('previewMeta');
const previewList = document.getElementById('previewList');
const progressContainer = document.getElementById('progressContainer');
const progressBar = document.getElementById('progressBar');
const progressLabel = document.getElementById('progressLabel');
const defaultDropZoneText = 'Trascina qui una cartella o un file .zip';
let isProcessing = false;
let currentPreviewKind = null;

function showProgress() {
  progressContainer.style.display = 'block';
  progressBar.removeAttribute('value');
  progressLabel.textContent = 'In corso...';
}

function hideProgress() {
  progressContainer.style.display = 'none';
}

let _indexFilesFound = 0;

function updateProgress({ phase, current, total, file, scanned, folder }) {
  if (phase === 'scan') {
    _indexFilesFound = 0;
    progressLabel.textContent = 'Scansione file sorgente...';
    progressBar.removeAttribute('value');
  } else if (phase === 'index-dest') {
    progressBar.max = total;
    progressBar.value = current;
    const filesInfo = _indexFilesFound > 0 ? `  —  ${_indexFilesFound} file CAD trovati` : '';
    progressLabel.textContent = `Analisi destinazione: ${current} / ${total}${folder ? `  —  ${folder}` : ''}${filesInfo}`;
  } else if (phase === 'index-dup') {
    if (current !== undefined && total !== undefined) {
      progressBar.max = total;
      progressBar.value = current;
      progressLabel.textContent = `Analisi destinazione: ${current} / ${total} cartelle`;
    } else {
      _indexFilesFound = scanned;
      const dirInfo = progressBar.max > 0 ? `${progressBar.value} / ${progressBar.max}  —  ` : '';
      progressLabel.textContent = `Analisi destinazione: ${dirInfo}${scanned} file CAD trovati`;
    }
  } else if (phase === 'copy') {
    progressBar.max = total;
    progressBar.value = current;
    progressLabel.textContent = `Smistamento: ${current} / ${total}${file ? `  —  ${file}` : ''}`;
  }
}

function setLoading(isLoading) {
  folderBtn.disabled = isLoading;
  zipBtn.disabled = isLoading;
}

function setDestinationLoading(isLoading) {
  destinationInput.disabled = isLoading;
  browseDestinationBtn.disabled = isLoading;
  saveDestinationBtn.disabled = isLoading;
  openUnroutedBtn.disabled = isLoading;
  openDuplicatesBtn.disabled = isLoading;
  openSkippedBtn.disabled = isLoading;
  clearPreviewBtn.disabled = isLoading;
}

function formatBytes(bytes) {
  const value = Number(bytes || 0);
  if (value < 1024) return `${value} B`;
  if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
  if (value < 1024 * 1024 * 1024) return `${(value / (1024 * 1024)).toFixed(1)} MB`;
  return `${(value / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}

function showPreview(kind, title, payload, emptyMessage) {
  const files = payload?.files || [];
  const directory = payload?.directory || '';
  const lines = files.length
    ? files.map((file) => `- ${file.relativePath} | ${formatBytes(file.size)}`).join('\n')
    : emptyMessage;

  currentPreviewKind = kind;
  previewTitle.textContent = title;
  previewMeta.textContent = `cartella: ${directory} | file totali: ${files.length}`;
  previewList.textContent = lines;
  previewOverlay.classList.add('visible');
}

function hidePreview() {
  currentPreviewKind = null;
  previewOverlay.classList.remove('visible');
}

async function loadPreviewData(kind) {
  if (kind === 'duplicates') return window.api.listDuplicatesFiles();
  if (kind === 'skipped') return window.api.listSkippedFiles();
  return window.api.listUnroutedFiles();
}

async function clearPreviewData(kind) {
  if (kind === 'duplicates') return window.api.clearDuplicatesFiles();
  if (kind === 'skipped') return window.api.clearSkippedFiles();
  return window.api.clearUnroutedFiles();
}

function renderResult(title, result) {
  const details = (result.details || []).slice(0, 20);
  const detailsText = details.length
    ? details
        .map((d) => (d.destination ? `- ${d.file} -> ${d.destination}` : `- ${d.file}: ${d.reason}`))
        .join('\n')
    : '- nessun dettaglio';

  output.textContent = [
    title,
    `scansionati: ${result.scanned ?? 0}`,
    `copiati: ${result.copied ?? 0}`,
    `saltati: ${result.skipped ?? 0}`,
    `non smistati: ${result.unrouted ?? 0}`,
    `duplicati: ${result.duplicates ?? 0}`,
    '',
    'dettagli (max 20):',
    detailsText,
  ].join('\n');
}

async function handleAction(actionName, actionFn) {
  if (isProcessing) {
    return;
  }

  isProcessing = true;
  setLoading(true);
  showProgress();
  window.api.onProgress(updateProgress);
  output.textContent = `${actionName} in corso...`;

  try {
    const result = await actionFn();

    if (!result || result.canceled) {
      output.textContent = `${actionName} annullato.`;
      return;
    }

    renderResult(actionName, result);
  } catch (error) {
    output.textContent = `${actionName} fallito:\n${error.message}`;
  } finally {
    window.api.offProgress();
    hideProgress();
    setLoading(false);
    isProcessing = false;
  }
}

folderBtn.addEventListener('click', () => handleAction('Process Folder', window.api.selectFolder));
zipBtn.addEventListener('click', () => handleAction('Process ZIP', window.api.selectZip));

function resetDropZoneText() {
  dropZone.textContent = defaultDropZoneText;
}

function setDropZoneError(message) {
  dropZone.textContent = message;
  dropZone.classList.add('error');
  setTimeout(() => {
    dropZone.classList.remove('error');
    resetDropZoneText();
  }, 1800);
}

dropZone.addEventListener('dragover', (event) => {
  event.preventDefault();
  dropZone.classList.add('active');
});

dropZone.addEventListener('dragleave', () => {
  dropZone.classList.remove('active');
});

window.addEventListener('dragover', (event) => {
  event.preventDefault();
});

window.addEventListener('drop', (event) => {
  if (event.target instanceof Node && dropZone.contains(event.target)) {
    return;
  }

  event.preventDefault();
});

dropZone.addEventListener('drop', async (event) => {
  event.preventDefault();
  dropZone.classList.remove('active');

  const droppedFile = event.dataTransfer?.files?.[0] || event.dataTransfer?.items?.[0]?.getAsFile?.();
  let droppedPath = '';
  if (droppedFile) {
    try {
      droppedPath = window.api.getPathForDroppedFile(droppedFile) || droppedFile.path || '';
    } catch {
      droppedPath = '';
    }
  }

  if (!droppedPath) {
    setDropZoneError('Elemento non valido. Trascina una cartella o un file .zip');
    return;
  }

  await handleAction('Process Drag & Drop', () => window.api.processDroppedPath(droppedPath));
});

browseDestinationBtn.addEventListener('click', async () => {
  try {
    setDestinationLoading(true);
    destinationStatus.textContent = 'Seleziona una cartella...';

    const result = await window.api.selectDestinationFolder();
    if (!result || result.canceled) {
      destinationStatus.textContent = 'Selezione annullata.';
      return;
    }

    destinationInput.value = result.path;
    destinationStatus.textContent = 'Cartella selezionata. Premi Salva.';
  } catch (error) {
    destinationStatus.textContent = `Errore: ${error.message}`;
  } finally {
    setDestinationLoading(false);
  }
});

saveDestinationBtn.addEventListener('click', async () => {
  const destination = destinationInput.value.trim();
  if (!destination) {
    destinationStatus.textContent = 'Inserisci una destinazione valida.';
    return;
  }

  try {
    setDestinationLoading(true);
    destinationStatus.textContent = 'Salvataggio in corso...';

    const result = await window.api.updateDestination(destination);
    destinationInput.value = result.destination;
    destinationStatus.textContent = 'Destinazione salvata.';
  } catch (error) {
    destinationStatus.textContent = `Errore: ${error.message}`;
  } finally {
    setDestinationLoading(false);
  }
});

openUnroutedBtn.addEventListener('click', async () => {
  try {
    setDestinationLoading(true);
    destinationStatus.textContent = 'Caricamento anteprima non smistati...';

    const result = await window.api.listUnroutedFiles();
    showPreview(
      'unrouted',
      'Anteprima __NON_SMISTATI',
      result,
      'Nessun file presente in __NON_SMISTATI.'
    );
    destinationStatus.textContent = `Anteprima caricata (${result.files?.length || 0} file).`;
  } catch (error) {
    destinationStatus.textContent = `Errore: ${error.message}`;
  } finally {
    setDestinationLoading(false);
  }
});

openDuplicatesBtn.addEventListener('click', async () => {
  try {
    setDestinationLoading(true);
    destinationStatus.textContent = 'Caricamento anteprima duplicati...';

    const result = await window.api.listDuplicatesFiles();
    showPreview('duplicates', 'Anteprima __DUPLICATI', result, 'Nessun file presente in __DUPLICATI.');
    destinationStatus.textContent = `Anteprima caricata (${result.files?.length || 0} file).`;
  } catch (error) {
    destinationStatus.textContent = `Errore: ${error.message}`;
  } finally {
    setDestinationLoading(false);
  }
});

openSkippedBtn.addEventListener('click', async () => {
  try {
    setDestinationLoading(true);
    destinationStatus.textContent = 'Caricamento anteprima saltati...';

    const result = await window.api.listSkippedFiles();
    showPreview('skipped', 'Anteprima __SALTATI', result, 'Nessun file presente in __SALTATI.');
    destinationStatus.textContent = `Anteprima caricata (${result.files?.length || 0} file).`;
  } catch (error) {
    destinationStatus.textContent = `Errore: ${error.message}`;
  } finally {
    setDestinationLoading(false);
  }
});

clearPreviewBtn.addEventListener('click', async () => {
  if (!currentPreviewKind) {
    return;
  }

  const isDuplicates = currentPreviewKind === 'duplicates';
  const isSkipped = currentPreviewKind === 'skipped';
  const confirmMessage = isDuplicates
    ? 'Confermi la pulizia della cartella __DUPLICATI?'
    : isSkipped
      ? 'Confermi la pulizia della cartella saltati?'
      : 'Confermi la pulizia della cartella non smistati?';

  if (!window.confirm(confirmMessage)) {
    return;
  }

  try {
    setDestinationLoading(true);
    destinationStatus.textContent = 'Pulizia cartella in corso...';

    const clearResult = await clearPreviewData(currentPreviewKind);
    const refreshed = await loadPreviewData(currentPreviewKind);
    const title = isDuplicates ? 'Anteprima __DUPLICATI' : isSkipped ? 'Anteprima __SALTATI' : 'Anteprima __NON_SMISTATI';
    const emptyMessage = isDuplicates
      ? 'Nessun file presente in __DUPLICATI.'
      : isSkipped
        ? 'Nessun file presente in __SALTATI.'
        : 'Nessun file presente in __NON_SMISTATI.';

    showPreview(currentPreviewKind, title, refreshed, emptyMessage);
    destinationStatus.textContent = `Cartella pulita: ${clearResult.directory}`;
  } catch (error) {
    destinationStatus.textContent = `Errore: ${error.message}`;
  } finally {
    setDestinationLoading(false);
  }
});


closePreviewBtn.addEventListener('click', hidePreview);
previewOverlay.addEventListener('click', (event) => {
  if (event.target === previewOverlay) {
    hidePreview();
  }
});

window.addEventListener('keydown', (event) => {
  if (event.key === 'Escape' && previewOverlay.classList.contains('visible')) {
    hidePreview();
  }
});

async function initConfigUI() {
  try {
    const destinationResult = await window.api.getDestination();
    destinationInput.value = destinationResult.destination || '';
    destinationStatus.textContent = '';
  } catch (error) {
    destinationStatus.textContent = 'Impossibile caricare la destinazione.';
  }
}

initConfigUI();
