import { api } from '../core/api.js';
import { $, escapeHtml } from '../core/dom.js';
import { normalizeUiText } from '../core/text.js';
import { importerParseReady, importerPendingFiles, isDictionaryImportFile, resetImporterPreview, setImporterFeedback, setImporterParseReady, setImporterPendingFiles, setImporterRunVisible } from './events.js';
import { setStatus } from './status-bar.js';

export function toggleImporterPanel(open) {
  const panel = $("importerPanel");
  const backdrop = $("importerPanelBackdrop");
  if (!panel) return;
  panel.hidden = !open;
  if (backdrop) backdrop.hidden = !open;
}


export function openImporterPanel() {
  setImporterPendingFiles([]);
  setImporterParseReady(false);
  resetImporterPreview();
  const feedbackEl = $("importerFeedback");
  if (feedbackEl) {
    feedbackEl.textContent = "";
    feedbackEl.classList.remove("importer-feedback--success", "importer-feedback--error");
  }
  toggleImporterPanel(true);
}


export function closeImporterPanel() {
  toggleImporterPanel(false);
}


export function renderImporterPreview(payload) {
  const previewEl = $("importerPreview");
  const importBtn = $("btnImporterRun");
  if (!previewEl) return;
  const summary = payload && payload.summary ? payload.summary : {};
  const reports = payload && Array.isArray(payload.reports) ? payload.reports : [];
  const rows = [];
  const errorRows = [];
  reports.forEach((report) => {
    const fileName =
      report.source_name ||
      String(report.source_db_path || "").split(/[\\/]/).pop() ||
      "DICTIONARY.db3";
    const tables = Array.isArray(report.tables) ? report.tables : [];
    tables.forEach((table) => {
      rows.push({
        file: fileName,
        field: table.field_name || table.table_name || "",
        rows: table.rows_seen || 0,
        unique: table.unique_values || 0,
        frequency: table.frequency_total || 0,
      });
    });
    const errors = Array.isArray(report.errors) ? report.errors : [];
    errors.forEach((errorText) => {
      errorRows.push({ file: fileName, error: String(errorText || "") });
    });
  });
  const body = rows.length
    ? rows
        .map(
          (r) =>
            `<tr><td>${escapeHtml(r.file)}</td><td>${escapeHtml(r.field)}</td><td>${r.rows}</td><td>${r.unique}</td><td>${r.frequency}</td></tr>`
        )
        .join("")
    : `<tr><td colspan="5">Aucune valeur importable trouv\u00e9e.</td></tr>`;
  const errorBlock = errorRows.length
    ? `<div class="importer-preview__errors"><strong>Erreurs d'analyse</strong><ul>${errorRows
        .map((r) => `<li><code>${escapeHtml(r.file)}</code>: ${escapeHtml(r.error)}</li>`)
        .join("")}</ul></div>`
    : "";
  previewEl.innerHTML = normalizeUiText(`
    <div class="importer-preview__summary">
      ${summary.files || 0} fichier(s), ${summary.fields_seen || 0} table(s), ${summary.unique_values || 0} valeur(s) unique(s), ${summary.rows_seen || 0} ligne(s)${summary.error_count ? `, ${summary.error_count} erreur(s)` : ""}.
    </div>
    ${errorBlock}
    <table class="importer-preview__table">
      <thead><tr><th>Fichier</th><th>Table</th><th>Lignes</th><th>Valeurs</th><th>Fr\u00e9quence</th></tr></thead>
      <tbody>${body}</tbody>
    </table>
  `);
  previewEl.hidden = false;
  setImporterParseReady(rows.length > 0);
  setImporterRunVisible(importerParseReady);
  if (importBtn) importBtn.disabled = !importerParseReady;
}


export async function uploadDictionaryFiles(fileList, action) {
  const files = Array.from(fileList || []);
  if (!files.length) {
    setImporterFeedback("Aucun fichier sélectionné.", true);
    resetImporterPreview();
    return;
  }
  const validFiles = files.filter((f) => isDictionaryImportFile(f));
  if (!validFiles.length) {
    setImporterFeedback(
      "Sélectionnez des fichiers DICTIONARY.db3 ou des dictionnaires client (.txt / .json).",
      true
    );
    resetImporterPreview();
    return;
  }
  const form = new FormData();
  form.append("action", action);
  if (action === "import") {
    form.append("confirm", "1");
  }
  validFiles.forEach((f) => form.append("files", f));
  try {
    const isImport = action === "import";
    setStatus(isImport ? "Import du dictionnaire général en cours..." : "Analyse du dictionnaire en cours...");
    setImporterFeedback(isImport ? "Import en cours..." : "Analyse en cours...", false);
    const resp = await fetch("/api/dictionary/general/import", {
      method: "POST",
      body: form,
    });
    const payload = await resp.json().catch(() => ({}));
    if (!resp.ok || !payload || payload.ok !== true) {
      const msg = (payload && payload.error) || (isImport ? "Import échoué" : "Analyse échouée");
      setImporterFeedback(msg, true);
      setStatus(msg, true);
      return;
    }
    const summary = payload.summary || {};
    if (isImport) {
      const msg = `Import termin\u00e9: ${summary.files || 0} fichier(s), ${summary.inserted || 0} ajout(s), ${summary.updated || 0} mise(s) \u00e0 jour.`;
      setImporterFeedback(msg, false);
      setStatus("Import du dictionnaire termin\u00e9.");
      setImporterParseReady(false);
      setImporterPendingFiles([]);
      setImporterRunVisible(false);
    } else {
      setImporterPendingFiles(validFiles);
      renderImporterPreview(payload);
      setImporterFeedback(
        importerParseReady
          ? "Analyse termin\u00e9e. V\u00e9rifiez le r\u00e9sum\u00e9 ci-dessous, puis cliquez sur Importer pour confirmer."
          : "Analyse termin\u00e9e sans valeur importable. Corrigez les fichiers ou les erreurs signal\u00e9es.",
        !importerParseReady
      );
      setStatus("Analyse du dictionnaire termin\u00e9e.");
    }
  } catch (e) {
    const msg = (e && e.message) || "Erreur pendant le traitement du dictionnaire";
    setImporterFeedback(msg, true);
    setStatus(msg, true);
  }
}


export async function parseDictionaryFiles(fileList) {
  setImporterPendingFiles([]);
  resetImporterPreview();
  await uploadDictionaryFiles(fileList, "parse");
}


export async function confirmDictionaryImport() {
  if (!importerParseReady || !importerPendingFiles.length) {
    setImporterFeedback(
      "Analysez d'abord les fichiers et v\u00e9rifiez le r\u00e9sum\u00e9 avant d'importer.",
      true
    );
    return;
  }
  await uploadDictionaryFiles(importerPendingFiles, "import");
}
