type BaseDialogOptions = {
  title: string;
  message: string;
  confirmLabel: string;
  cancelLabel?: string;
  tone?: 'danger' | 'warning' | 'neutral';
  inputLabel?: string;
  inputPlaceholder?: string;
  requiredText?: string;
  requiredHint?: string;
};

let stylesInjected = false;
let activeOverlay: HTMLElement | null = null;

export async function confirmDeletionWithTyping(
  targetLabel?: string,
  confirmWord = 'EXCLUIR'
): Promise<boolean> {
  const normalizedWord = confirmWord.trim().toUpperCase();
  const label = (targetLabel || 'este registro').trim();

  return openDialog({
    title: 'Confirmar Exclusão',
    message: `Tem certeza que deseja excluir ${label}? Esta ação não poderá ser desfeita.`,
    confirmLabel: 'Excluir',
    cancelLabel: 'Cancelar',
    tone: 'danger',
    inputLabel: `Digite ${normalizedWord} para confirmar`,
    inputPlaceholder: normalizedWord,
    requiredText: normalizedWord,
    requiredHint: `A exclusão só será confirmada se você digitar ${normalizedWord}.`,
  });
}

export async function showDeletionWarning(message: string, title = 'Atenção'): Promise<void> {
  await openDialog({
    title,
    message,
    confirmLabel: 'Entendi',
    tone: 'warning',
  });
}

export async function confirmActionModal(options: {
  title: string;
  message: string;
  confirmLabel: string;
  cancelLabel?: string;
  tone?: 'danger' | 'warning' | 'neutral';
}): Promise<boolean> {
  return openDialog({
    title: options.title,
    message: options.message,
    confirmLabel: options.confirmLabel,
    cancelLabel: options.cancelLabel ?? 'Cancelar',
    tone: options.tone ?? 'neutral',
  });
}

function openDialog(options: BaseDialogOptions): Promise<boolean> {
  if (typeof document === 'undefined') {
    return Promise.resolve(false);
  }

  if (activeOverlay) {
    activeOverlay.remove();
    activeOverlay = null;
  }

  ensureStyles();

  return new Promise<boolean>((resolve) => {
    const overlay = document.createElement('div');
    overlay.className = 'lgx-confirm-overlay';

    const card = document.createElement('div');
    card.className = `lgx-confirm-card tone-${options.tone || 'neutral'}`;
    card.setAttribute('role', 'dialog');
    card.setAttribute('aria-modal', 'true');
    card.setAttribute('aria-label', options.title);

    const icon = getToneIcon(options.tone || 'neutral');
    const hasInput = !!options.requiredText;

    card.innerHTML = `
      <div class="lgx-confirm-head">
        <div class="lgx-confirm-icon">${icon}</div>
        <div>
          <h3>${escapeHtml(options.title)}</h3>
          <p>${escapeHtml(options.message)}</p>
        </div>
      </div>
      ${
        hasInput
          ? `
        <div class="lgx-confirm-field">
          <label>${escapeHtml(options.inputLabel || '')}</label>
          <input type="text" autocomplete="off" placeholder="${escapeHtml(options.inputPlaceholder || '')}" />
          <small>${escapeHtml(options.requiredHint || '')}</small>
        </div>
      `
          : ''
      }
      <div class="lgx-confirm-actions">
        ${
          options.cancelLabel
            ? `<button type="button" class="lgx-btn ghost js-cancel">${escapeHtml(options.cancelLabel)}</button>`
            : ''
        }
        <button type="button" class="lgx-btn ${options.tone === 'danger' ? 'danger' : 'primary'} js-confirm" ${
          hasInput ? 'disabled' : ''
        }>${escapeHtml(options.confirmLabel)}</button>
      </div>
    `;

    overlay.appendChild(card);
    document.body.appendChild(overlay);
    activeOverlay = overlay;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    const input = hasInput ? (card.querySelector('input') as HTMLInputElement | null) : null;
    const confirmBtn = card.querySelector('.js-confirm') as HTMLButtonElement | null;
    const cancelBtn = card.querySelector('.js-cancel') as HTMLButtonElement | null;
    const requiredText = (options.requiredText || '').trim().toUpperCase();

    const cleanup = (result: boolean) => {
      document.removeEventListener('keydown', onKeyDown);
      overlay.remove();
      if (activeOverlay === overlay) activeOverlay = null;
      document.body.style.overflow = prevOverflow;
      resolve(result);
    };

    const canConfirm = () => {
      if (!hasInput) return true;
      return (input?.value || '').trim().toUpperCase() === requiredText;
    };

    const updateConfirmState = () => {
      if (!confirmBtn) return;
      confirmBtn.disabled = !canConfirm();
    };

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        event.preventDefault();
        cleanup(false);
      }
      if (event.key === 'Enter') {
        if (document.activeElement === cancelBtn) return;
        if (canConfirm()) {
          event.preventDefault();
          cleanup(true);
        }
      }
    };

    overlay.addEventListener('click', (event) => {
      if (event.target === overlay) cleanup(false);
    });

    cancelBtn?.addEventListener('click', () => cleanup(false));
    confirmBtn?.addEventListener('click', () => cleanup(canConfirm()));
    input?.addEventListener('input', updateConfirmState);
    input?.addEventListener('paste', () => setTimeout(updateConfirmState));
    document.addEventListener('keydown', onKeyDown);

    const focusTarget = input ?? cancelBtn ?? confirmBtn;
    setTimeout(() => focusTarget?.focus(), 0);
  });
}

function ensureStyles() {
  if (stylesInjected || typeof document === 'undefined') return;

  const style = document.createElement('style');
  style.id = 'lgx-confirm-modal-styles';
  style.textContent = `
    .lgx-confirm-overlay {
      position: fixed;
      inset: 0;
      background: rgba(15, 23, 42, 0.5);
      backdrop-filter: blur(2px);
      display: grid;
      place-items: center;
      z-index: 5000;
      padding: 16px;
      animation: lgxFadeIn .12s ease-out;
    }
    .lgx-confirm-card {
      width: min(460px, calc(100vw - 32px));
      background: #fff;
      border: 1px solid #e5e7eb;
      border-radius: 16px;
      box-shadow: 0 24px 60px rgba(15, 23, 42, 0.18);
      padding: 18px;
      animation: lgxScaleIn .14s ease-out;
      font-family: inherit;
      color: #111827;
    }
    .lgx-confirm-head {
      display: grid;
      grid-template-columns: 40px 1fr;
      gap: 12px;
      align-items: start;
    }
    .lgx-confirm-icon {
      width: 40px;
      height: 40px;
      border-radius: 999px;
      display: grid;
      place-items: center;
      font-size: 18px;
      font-weight: 700;
      background: #f3f4f6;
      color: #374151;
    }
    .lgx-confirm-card h3 {
      margin: 2px 0 6px;
      font-size: 16px;
      font-weight: 700;
      line-height: 1.2;
    }
    .lgx-confirm-card p {
      margin: 0;
      font-size: 13px;
      color: #6b7280;
      line-height: 1.4;
    }
    .lgx-confirm-field {
      margin-top: 14px;
      display: grid;
      gap: 6px;
    }
    .lgx-confirm-field label {
      font-size: 12px;
      font-weight: 600;
      color: #111827;
    }
    .lgx-confirm-field input {
      height: 40px;
      border: 1px solid #d1d5db;
      border-radius: 10px;
      padding: 0 12px;
      font-size: 14px;
      outline: none;
      transition: border-color .15s ease, box-shadow .15s ease;
    }
    .lgx-confirm-field input:focus {
      border-color: #dc2626;
      box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.12);
    }
    .lgx-confirm-field small {
      font-size: 11px;
      color: #6b7280;
    }
    .lgx-confirm-actions {
      margin-top: 16px;
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
    .lgx-btn {
      height: 38px;
      border-radius: 10px;
      border: 1px solid transparent;
      padding: 0 14px;
      font-size: 13px;
      font-weight: 600;
      cursor: pointer;
    }
    .lgx-btn.ghost {
      background: #fff;
      color: #374151;
      border-color: #d1d5db;
    }
    .lgx-btn.ghost:hover { background: #f9fafb; }
    .lgx-btn.primary {
      background: #1d4ed8;
      color: #fff;
      border-color: #1d4ed8;
    }
    .lgx-btn.primary:hover:not(:disabled) { background: #1e40af; border-color: #1e40af; }
    .lgx-btn.danger {
      background: #dc2626;
      color: #fff;
      border-color: #dc2626;
    }
    .lgx-btn.danger:hover:not(:disabled) { background: #b91c1c; border-color: #b91c1c; }
    .lgx-btn:disabled {
      opacity: .6;
      cursor: not-allowed;
    }
    .lgx-confirm-card.tone-danger .lgx-confirm-icon {
      background: #fee2e2;
      color: #b91c1c;
    }
    .lgx-confirm-card.tone-warning .lgx-confirm-icon {
      background: #fef3c7;
      color: #b45309;
    }
    .lgx-confirm-card.tone-warning .lgx-btn.primary {
      background: #d97706;
      border-color: #d97706;
    }
    .lgx-confirm-card.tone-warning .lgx-btn.primary:hover:not(:disabled) {
      background: #b45309;
      border-color: #b45309;
    }
    @keyframes lgxFadeIn { from { opacity: 0; } to { opacity: 1; } }
    @keyframes lgxScaleIn { from { opacity: 0; transform: translateY(6px) scale(.98); } to { opacity: 1; transform: translateY(0) scale(1); } }
  `;

  document.head.appendChild(style);
  stylesInjected = true;
}

function getToneIcon(tone: BaseDialogOptions['tone']): string {
  if (tone === 'danger') return '!';
  if (tone === 'warning') return '!';
  return 'i';
}

function escapeHtml(value: string): string {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}
