import { $ } from '../core/dom.js';
import { normalizeUiText } from '../core/text.js';
import { state, runtime } from '../state/app-state.js';
import { resolveLotAssignment } from './events.js';

export function showRecordInsertOverlay() {
  runtime.recordInsertOverlayDepth += 1;
  const panel = $("recordInsertOverlay");
  const backdrop = $("recordInsertBackdrop");
  if (panel) panel.hidden = false;
  if (backdrop) backdrop.hidden = false;
}


export function hideRecordInsertOverlay() {
  runtime.recordInsertOverlayDepth = Math.max(0, runtime.recordInsertOverlayDepth - 1);
  if (runtime.recordInsertOverlayDepth > 0) return;
  const panel = $("recordInsertOverlay");
  const backdrop = $("recordInsertBackdrop");
  if (panel) panel.hidden = true;
  if (backdrop) backdrop.hidden = true;
}


export function showHeaderAddOverlay() {
  runtime.headerAddOverlayDepth += 1;
  const panel = $("headerAddOverlay");
  const backdrop = $("headerAddBackdrop");
  if (panel) panel.hidden = false;
  if (backdrop) backdrop.hidden = false;
}


export function hideHeaderAddOverlay() {
  runtime.headerAddOverlayDepth = Math.max(0, runtime.headerAddOverlayDepth - 1);
  if (runtime.headerAddOverlayDepth > 0) return;
  const panel = $("headerAddOverlay");
  const backdrop = $("headerAddBackdrop");
  if (panel) panel.hidden = true;
  if (backdrop) backdrop.hidden = true;
}

export function showHeaderDeleteOverlay() {
  runtime.headerDeleteOverlayDepth += 1;
  const panel = $("headerDeleteOverlay");
  const backdrop = $("headerDeleteBackdrop");
  if (panel) panel.hidden = false;
  if (backdrop) backdrop.hidden = false;
}


export function hideHeaderDeleteOverlay() {
  runtime.headerDeleteOverlayDepth = Math.max(0, runtime.headerDeleteOverlayDepth - 1);
  if (runtime.headerDeleteOverlayDepth > 0) return;
  const panel = $("headerDeleteOverlay");
  const backdrop = $("headerDeleteBackdrop");
  if (panel) panel.hidden = true;
  if (backdrop) backdrop.hidden = true;
}


export function showRecordDeleteOverlay() {
  runtime.recordDeleteOverlayDepth += 1;
  const panel = $("recordDeleteOverlay");
  const backdrop = $("recordDeleteBackdrop");
  if (panel) panel.hidden = false;
  if (backdrop) backdrop.hidden = false;
}


export function hideRecordDeleteOverlay() {
  runtime.recordDeleteOverlayDepth = Math.max(0, runtime.recordDeleteOverlayDepth - 1);
  if (runtime.recordDeleteOverlayDepth > 0) return;
  const panel = $("recordDeleteOverlay");
  const backdrop = $("recordDeleteBackdrop");
  if (panel) panel.hidden = true;
  if (backdrop) backdrop.hidden = true;
}


/**
 * Show the shared Annuler/OK confirmation panel.
 * @param {string} title
 * @param {string} message
 * @param {string} okLabel
 * @param {{
 *   cancelLabel?: string,
 *   kind?: "default"|"danger",
 *   warningText?: string,
 * }} [options]
 * @returns {Promise<boolean>}
 */
export function showConfirmActionPanel(title, message, okLabel, options) {
  return new Promise((resolve) => {
    runtime.confirmActionResolver = resolve;
    const opts = options || {};
    const panel = $("confirmActionPanel");
    const backdrop = $("confirmActionBackdrop");
    const titleEl = $("confirmActionTitle");
    const warningEl = $("confirmActionWarning");
    const msgEl = $("confirmActionMessage");
    const okBtn = $("btnConfirmActionOk");
    const cancelBtn = $("btnConfirmActionCancel");
    if (titleEl) titleEl.textContent = normalizeUiText(title || "Confirmation");
    const warningText = String(opts.warningText || "").trim();
    if (warningEl) {
      warningEl.textContent = warningText ? normalizeUiText(warningText) : "";
      warningEl.hidden = !warningText;
    }
    if (msgEl) msgEl.textContent = normalizeUiText(message || "");
    if (okBtn) okBtn.textContent = normalizeUiText(okLabel || "Confirmer");
    if (cancelBtn) cancelBtn.textContent = normalizeUiText(opts.cancelLabel || "Annuler");
    if (okBtn) {
      const isDanger = opts.kind === "danger";
      okBtn.classList.toggle("btn--danger", isDanger);
      okBtn.classList.toggle("btn--primary", !isDanger);
    }
    if (panel) panel.hidden = false;
    if (backdrop) backdrop.hidden = false;
  });
}


/**
 * Ask the operator to type one of the accepted values before confirming.
 * @param {{
 *   title?: string,
 *   message?: string,
 *   inputLabel?: string,
 *   expectedValues?: string[],
 *   okLabel?: string,
 *   kind?: "default"|"danger",
 * }} options
 * @returns {Promise<boolean>}
 */
export function showTypeToConfirmPanel(options) {
  return new Promise((resolve) => {
    const opts = options || {};
    const expectedValues = Array.isArray(opts.expectedValues)
      ? opts.expectedValues.map((value) => String(value || "").trim()).filter(Boolean)
      : [];
    runtime.typeToConfirmResolver = resolve;
    runtime.typeToConfirmExpectedValues = expectedValues;
    const panel = $("typeToConfirmPanel");
    const backdrop = $("typeToConfirmBackdrop");
    const titleEl = $("typeToConfirmTitle");
    const msgEl = $("typeToConfirmMessage");
    const inputLabelEl = $("typeToConfirmInputLabel");
    const input = $("typeToConfirmInput");
    const okBtn = $("btnTypeToConfirmOk");
    if (!panel || !backdrop || !input || !okBtn) {
      runtime.typeToConfirmResolver = null;
      runtime.typeToConfirmExpectedValues = [];
      resolve(false);
      return;
    }
    if (titleEl) titleEl.textContent = normalizeUiText(opts.title || "Confirmation");
    if (msgEl) msgEl.textContent = normalizeUiText(opts.message || "");
    if (inputLabelEl) {
      inputLabelEl.textContent = normalizeUiText(opts.inputLabel || "Confirmation");
    }
    okBtn.textContent = normalizeUiText(opts.okLabel || "Confirmer");
    const isDanger = opts.kind === "danger";
    okBtn.classList.toggle("btn--danger", isDanger);
    okBtn.classList.toggle("btn--primary", !isDanger);
    input.value = "";
    okBtn.disabled = true;
    panel.hidden = false;
    backdrop.hidden = false;
    requestAnimationFrame(() => input.focus());
  });
}

export function showAutocorrectChoicePanel(status) {
  return new Promise((resolve) => {
    runtime.autocorrectChoiceResolver = resolve;
    const panel = $("autocorrectChoicePanel");
    const backdrop = $("autocorrectChoiceBackdrop");
    const hint = $("autocorrectChoiceHint");
    const aiBtn = $("btnAutocorrectChoiceAi");
    const aiAvailable = !!(status && status.available);
    if (hint) {
      if (aiAvailable) {
        hint.textContent = normalizeUiText(`AI disponible via la passerelle Datafix (${status.model || "modèle configuré"}).`);
      } else if (status && status.configured) {
        hint.textContent = "AI indisponible : la passerelle Datafix n'est pas joignable pour le moment.";
      } else {
        hint.textContent = "AI indisponible : activez ce PC avec un code Datafix.";
      }
    }
    if (aiBtn) {
      aiBtn.disabled = !aiAvailable;
      aiBtn.title = aiAvailable ? "Corriger par AI" : (hint ? hint.textContent : "AI indisponible");
    }
    if (panel) panel.hidden = false;
    if (backdrop) backdrop.hidden = false;
  });
}


export function showLotAssignmentPanel(params) {
  return new Promise((resolve) => {
    runtime.lotAssignmentResolver = resolve;
    const panel = $("lotAssignmentPanel");
    const backdrop = $("lotAssignmentBackdrop");
    const titleEl = $("lotAssignmentTitle");
    const msgEl = $("lotAssignmentMessage");
    const hintEl = $("lotAssignmentHint");
    const selectEl = $("lotAssignmentSelect");
    const neverShowEl = $("lotAssignmentNeverShow");
    if (!panel || !backdrop || !msgEl || !hintEl || !selectEl) {
      resolveLotAssignment({ action: "skip" });
      return;
    }

    const batchName = String((params && params.batchName) || state.batch || "").trim();
    const suggested = String((params && params.suggestedSubProject) || "").trim();
    const mandatory = !!(params && params.mandatory);
    const needsBootstrap = !!(params && params.needsBootstrap);
    const candidates = Array.isArray(params && params.candidateSubProjects)
      ? params.candidateSubProjects.map((n) => String(n || "").trim()).filter(Boolean)
      : [];
    const options = Array.isArray(params && params.options)
      ? params.options.map((n) => String(n || "").trim()).filter(Boolean)
      : [];
    const detectedSubProject = suggested || (options[0] || "");

    if (titleEl) {
      titleEl.textContent = mandatory
        ? "Sous-projet requis"
        : "Affectation du lot";
    }
    if (needsBootstrap) {
      msgEl.textContent = normalizeUiText(
        `Le lot « ${batchName} » contient des images mais aucune base de données. ` +
        "Choisissez un sous-projet pour générer la base de sortie."
      );
      hintEl.textContent = normalizeUiText(
        "Les images seront enregistrées avec le DocType UNKNOWN jusqu'à modification manuelle."
      );
    } else if (mandatory) {
      msgEl.textContent = normalizeUiText(
        `Le lot « ${batchName} » requiert l'affectation d'un sous-projet.`
      );
      hintEl.textContent = normalizeUiText(
        "Sélectionnez le sous-projet correspondant à ce lot."
      );
    } else {
      msgEl.textContent = normalizeUiText(
        `Lot "${batchName}" détecté comme ${detectedSubProject || "Sous-projet non défini"}.`
      );
      hintEl.textContent = normalizeUiText(
        "Vous pouvez sélectionner un autre sous-projet dans la liste déroulante pour l'affecter à ce lot."
      );
    }
    if (neverShowEl) {
      const neverShowWrap = neverShowEl.closest(".lot-assignment-panel__never-show");
      if (neverShowWrap) neverShowWrap.hidden = mandatory;
    }

    selectEl.innerHTML = "";
    const appended = new Set();
    const appendOption = (name) => {
      const clean = String(name || "").trim();
      if (!clean || appended.has(clean)) return;
      const opt = document.createElement("option");
      opt.value = clean;
      opt.textContent = clean;
      selectEl.appendChild(opt);
      appended.add(clean);
    };

    if (suggested) appendOption(suggested);
    candidates.forEach(appendOption);
    options.forEach(appendOption);
    if (!appended.size) {
      const opt = document.createElement("option");
      opt.value = "";
      opt.textContent = "(Aucun sous-projet disponible)";
      selectEl.appendChild(opt);
    }

    if (suggested && appended.has(suggested)) {
      selectEl.value = suggested;
    } else if (selectEl.options.length > 0) {
      selectEl.selectedIndex = 0;
    }
    if (neverShowEl) neverShowEl.checked = !state.showLotAssignmentPrompt;

    panel.hidden = false;
    backdrop.hidden = false;
    selectEl.focus();
  });
}


/**
 * Ask the operator to type the sub-project name before confirming deletion.
 * @param {string} subProjectName
 * @returns {Promise<boolean>}
 */
export function showSubProjectDeleteConfirmPanel(subProjectName) {
  const name = String(subProjectName || "").trim();
  const result = showTypeToConfirmPanel({
    title: "Supprimer le sous-projet",
    message: name
      ? `Cette action est irréversible.\nPour confirmer, saisissez le nom exact du sous-projet « ${name} ».`
      : "Cette action est irréversible.\nPour confirmer, saisissez le nom exact du sous-projet.",
    inputLabel: "Nom du sous-projet",
    expectedValues: [name],
    okLabel: "Supprimer",
    kind: "danger",
  });
  runtime.subProjectDeleteConfirmResolver = true;
  return result.finally(() => {
    runtime.subProjectDeleteConfirmResolver = null;
  });
}
