import { isDarkTheme, toggleTheme } from '../services/theme.js';
import { icons } from '../services/icons.js';
import { apiGet, apiPut } from '../services/apiClient.js';
import { showToast } from '../services/toast.js';
import { encryptVeriFactuPassword, formatVeriFactuError, getVeriFactuFormats, getVeriFactuHealth, registerVeriFactuCertificate } from '../services/verifactu.js';

function decodeTokenPayload(token) {
  try {
    const payloadPart = token.split('.')[1];
    if (!payloadPart) return null;
    const base64 = payloadPart.replace(/-/g, '+').replace(/_/g, '/');
    return JSON.parse(atob(base64));
  } catch {
    return null;
  }
}

function formatSeconds(totalSeconds) {
  if (totalSeconds <= 0) return 'Expirada';
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;

  const hh = String(hours).padStart(2, '0');
  const mm = String(minutes).padStart(2, '0');
  const ss = String(seconds).padStart(2, '0');
  return `${hh}:${mm}:${ss}`;
}

function getTokenExpirationInfo() {
  const token = localStorage.getItem('token');
  if (!token) {
    return { hasToken: false, expiresAtText: 'No hay token', remainingText: 'No autenticado' };
  }

  const payload = decodeTokenPayload(token);
  if (!payload || !payload.exp) {
    return { hasToken: true, expiresAtText: 'No disponible', remainingText: 'No disponible' };
  }

  const expiresAtMs = payload.exp * 1000;
  const nowMs = Date.now();
  const remainingSeconds = Math.max(0, Math.floor((expiresAtMs - nowMs) / 1000));

  return {
    hasToken: true,
    expiresAtText: new Date(expiresAtMs).toLocaleString('es-ES'),
    remainingText: formatSeconds(remainingSeconds),
    remainingSeconds
  };
}

export function renderSettingsPage() {
  const container = document.createElement('div');
  container.className = 'settings-page';

  const dark = isDarkTheme();

  container.innerHTML = `
    <div class="settings-header">
      <h1>Configuración</h1>
      <p>Preferencias visuales y estado de sesión.</p>
    </div>

    <div class="settings-grid">
      <section class="settings-card">
        <h2>Apariencia</h2>
        <div class="settings-row">
          <div>
            <p class="settings-label">Modo oscuro</p>
            <p class="settings-help">Cambia entre tema claro y oscuro.</p>
          </div>
          <button type="button" class="settings-theme-toggle ${dark ? 'settings-theme-toggle--active' : ''}" id="settings-theme-toggle" aria-pressed="${dark ? 'true' : 'false'}">
            <span class="toggle-track">
              <span class="toggle-icons">
                <span class="toggle-icon-sun">${icons.sun}</span>
                <span class="toggle-icon-moon">${icons.moon}</span>
              </span>
              <span class="toggle-thumb"></span>
            </span>
          </button>
        </div>
      </section>

      <section class="settings-card settings-card--session">
        <h2>Sesión</h2>
        <div class="settings-session-list">
          <div class="settings-session-item">
            <div class="settings-session-item-label">
              <span class="settings-session-icon">${icons.info}</span>
              <span>Caducidad del token</span>
            </div>
            <strong id="token-expire-at">-</strong>
          </div>
          <div class="settings-session-item">
            <div class="settings-session-item-label">
              <span class="settings-session-icon">${icons.clock}</span>
              <span>Tiempo restante</span>
            </div>
            <strong id="token-remaining">-</strong>
          </div>
        </div>
      </section>

      <section class="settings-card" style="grid-column:1/-1">
        <h2>Notificaciones</h2>
        <p class="settings-help" style="margin-bottom:1rem">
          URL de webhook para notificaciones de cambio de estado de facturas (compatible con Teams y Slack).
          Déjalo vacío para desactivar.
        </p>
        <div class="settings-row" style="flex-direction:column;align-items:stretch;gap:0.75rem">
          <input
            type="url"
            id="webhook-url-input"
            placeholder="https://outlook.office.com/webhook/... o https://hooks.slack.com/..."
            style="width:100%;padding:0.6rem 0.75rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary);font-size:0.9rem"
          />
          <div style="display:flex;gap:0.75rem;justify-content:flex-end">
            <button type="button" class="btn-cancel-compact" id="webhook-clear-btn">Limpiar</button>
            <button type="button" class="btn-submit-compact" id="webhook-save-btn">Guardar URL</button>
          </div>
          <p id="webhook-status" style="font-size:0.8rem;color:var(--text-secondary);min-height:1.2em"></p>
        </div>
      </section>

      <section class="settings-card" style="grid-column:1/-1">
        <h2>VeriFactu</h2>
        <p class="settings-help" style="margin-bottom:1rem">
          Conexión con VeriFactu MidAPI para validar el enlace, registrar certificados y preparar el envío de facturas.
        </p>
        <div class="settings-row" style="flex-direction:column;align-items:stretch;gap:0.75rem">
          <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:0.75rem;">
            <input
              type="text"
              id="verifactu-cert-name"
              placeholder="Nombre del certificado"
              style="width:100%;padding:0.6rem 0.75rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary);font-size:0.9rem"
            />
            <label style="display:flex;flex-direction:column;gap:0.25rem;font-size:0.85rem;color:var(--text-secondary)">
              Archivo .p12
              <input
                type="file"
                id="verifactu-cert-file"
                accept=".p12"
                style="padding:0.4rem 0;font-size:0.85rem;color:var(--text-primary)"
              />
            </label>
          </div>
          <input
            type="password"
            id="verifactu-cert-password"
            placeholder="Contraseña del certificado"
            style="width:100%;padding:0.6rem 0.75rem;border:1px solid var(--border-color);border-radius:6px;background:var(--bg-primary);color:var(--text-primary);font-size:0.9rem"
          />
          <div style="display:flex;gap:0.75rem;justify-content:flex-end;flex-wrap:wrap">
            <button type="button" class="btn-cancel-compact" id="verifactu-health-btn">Comprobar API</button>
            <button type="button" class="btn-cancel-compact" id="verifactu-formats-btn">Ver formatos</button>
            <button type="button" class="btn-submit-compact" id="verifactu-register-btn">Registrar certificado</button>
          </div>
          <p id="verifactu-status" style="font-size:0.8rem;color:var(--text-secondary);min-height:1.2em"></p>
        </div>
      </section>
    </div>
  `;

  const themeBtn = container.querySelector('#settings-theme-toggle');
  const expireAtEl = container.querySelector('#token-expire-at');
  const remainingEl = container.querySelector('#token-remaining');

  const renderThemeButton = () => {
    const isDark = isDarkTheme();
    themeBtn.classList.toggle('settings-theme-toggle--active', isDark);
    themeBtn.setAttribute('aria-pressed', isDark ? 'true' : 'false');
  };

  const renderTokenInfo = () => {
    const info = getTokenExpirationInfo();
    expireAtEl.textContent = info.expiresAtText;
    remainingEl.textContent = info.remainingText;

    if (info.remainingSeconds === 0 && info.hasToken) {
      remainingEl.classList.add('settings-token-expired');
    } else {
      remainingEl.classList.remove('settings-token-expired');
    }
  };

  renderThemeButton();
  renderTokenInfo();

  themeBtn.addEventListener('click', () => {
    toggleTheme();
    renderThemeButton();
  });

  const intervalId = setInterval(renderTokenInfo, 1000);

  // Webhook config
  const webhookInput = container.querySelector('#webhook-url-input');
  const webhookStatus = container.querySelector('#webhook-status');
  const verifactuStatus = container.querySelector('#verifactu-status');
  const verifactuCertName = container.querySelector('#verifactu-cert-name');
  const verifactuCertFile = container.querySelector('#verifactu-cert-file');
  const verifactuCertPassword = container.querySelector('#verifactu-cert-password');

  verifactuCertFile.addEventListener('change', () => {
    const file = verifactuCertFile.files?.[0];
    if (!file) return;

    if (!file.name.toLowerCase().endsWith('.p12')) {
      verifactuCertFile.value = '';
      showToast('Solo se permite subir archivos con extension .p12', 'error');
    }
  });

  async function loadWebhookUrl() {
    try {
      const data = await apiGet('/api/Settings/webhook');
      webhookInput.value = data.url || '';
      webhookStatus.textContent = data.url ? 'Webhook configurado.' : 'Sin webhook configurado.';
    } catch {
      webhookStatus.textContent = 'No se pudo cargar la configuración.';
    }
  }

  container.querySelector('#webhook-save-btn').addEventListener('click', async () => {
    const saveBtn = container.querySelector('#webhook-save-btn');
    saveBtn.disabled = true;
    try {
      await apiPut('/api/Settings/webhook', { url: webhookInput.value.trim() });
      showToast('URL de webhook guardada', 'success');
      webhookStatus.textContent = webhookInput.value.trim() ? 'Webhook configurado.' : 'Sin webhook configurado.';
    } catch (err) {
      showToast(`Error: ${err.message}`, 'error');
    } finally {
      saveBtn.disabled = false;
    }
  });

  container.querySelector('#webhook-clear-btn').addEventListener('click', () => {
    webhookInput.value = '';
  });

  container.querySelector('#verifactu-health-btn').addEventListener('click', async () => {
    const button = container.querySelector('#verifactu-health-btn');
    button.disabled = true;
    verifactuStatus.textContent = 'Consultando estado de VeriFactu...';
    try {
      const health = await getVeriFactuHealth();
      if (health?.status === 'down') {
        verifactuStatus.textContent = `VeriFactu no responde: ${health.error || 'sin detalle'}`;
        showToast('VeriFactu no está disponible en 6789', 'error');
      } else {
        verifactuStatus.textContent = `API activa: ${health.status || 'ok'}`;
        showToast('VeriFactu responde correctamente', 'success');
      }
    } catch (error) {
      verifactuStatus.textContent = `Error al comprobar la API: ${error.message}`;
      showToast(`VeriFactu: ${error.message}`, 'error');
    } finally {
      button.disabled = false;
    }
  });

  container.querySelector('#verifactu-formats-btn').addEventListener('click', async () => {
    const button = container.querySelector('#verifactu-formats-btn');
    button.disabled = true;
    verifactuStatus.textContent = 'Cargando formatos soportados...';
    try {
      const data = await getVeriFactuFormats();
      const formats = Array.isArray(data.formats) ? data.formats.join(', ') : 'sin datos';
      verifactuStatus.textContent = `Formatos soportados: ${formats}`;
    } catch (error) {
      verifactuStatus.textContent = `Error al cargar formatos: ${error.message}`;
      showToast(`VeriFactu: ${error.message}`, 'error');
    } finally {
      button.disabled = false;
    }
  });

  container.querySelector('#verifactu-register-btn').addEventListener('click', async () => {
    const button = container.querySelector('#verifactu-register-btn');
    const certName = verifactuCertName.value.trim();
    const file = verifactuCertFile.files?.[0];
    const password = verifactuCertPassword.value;

    if (!certName || !file || !password) {
      showToast('Rellena nombre, selecciona el archivo .p12 y escribe la contraseña', 'error');
      return;
    }

    if (!file.name.toLowerCase().endsWith('.p12')) {
      showToast('El certificado debe tener extension .p12', 'error');
      return;
    }

    let cert_file;
    try {
      cert_file = await new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result.split(',')[1]);
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });
    } catch {
      showToast('No se pudo leer el archivo .p12', 'error');
      return;
    }

    let password_encrypted;
    try {
      console.log('[DEBUG] Password before encryption:', password);
      password_encrypted = await encryptVeriFactuPassword(password);
      console.log('[DEBUG] Encrypted password:', password_encrypted);
    } catch (error) {
      showToast(`No se pudo cifrar la contraseña: ${error.message}`, 'error');
      return;
    }

    button.disabled = true;
    verifactuStatus.textContent = 'Registrando certificado en VeriFactu...';
    try {
      const result = await registerVeriFactuCertificate({
        cert_name: certName,
        cert_file,
        password: password_encrypted
      });

      if (result?.success === false) {
        const errorMessage = formatVeriFactuError(result.error);
        verifactuStatus.textContent = `Error al registrar certificado: ${errorMessage}`;
        showToast(`VeriFactu: ${errorMessage}`, 'error');
        return;
      }

      const token = result.token ? ` Token: ${result.token}` : '';
      verifactuStatus.textContent = `Certificado registrado.${token}`;
      showToast('Certificado registrado en VeriFactu', 'success');
    } catch (error) {
      const errorMessage = formatVeriFactuError(error);
      verifactuStatus.textContent = `Error al registrar certificado: ${errorMessage}`;
      showToast(`VeriFactu: ${errorMessage}`, 'error');
    } finally {
      button.disabled = false;
    }
  });

  loadWebhookUrl();

  container.cleanup = () => clearInterval(intervalId);

  return container;
}