import { renderHeader } from '../components/header.js';
import { state } from '../state.js';
import { loadEncryptedUserSecrets } from '../services/key-vault.js';
import {
  describeTransferKeys,
  makeKeyTransferText,
  renderQrSvg,
} from '../services/qr-key-transfer-service.js';

export const pageMeta = { id: 'device-qr-view', title: 'Показать QR-код' };

export function render({ navigate }) {
  const screen = document.createElement('section');
  screen.className = 'stack';

  screen.append(
    renderHeader({
      title: 'Показать QR-код',
      leftAction: { label: '←', onClick: () => navigate('connect-device-view') },
    }),
  );

  const card = document.createElement('div');
  card.className = 'card stack qr-card';
  card.innerHTML = `
    <div class="qr-image" id="device-transfer-qr" aria-label="QR-код для переноса ключей"></div>
    <p class="meta-muted" id="device-transfer-login">Логин: ...</p>
    <p class="meta-muted" id="device-transfer-keys">Ключи: ...</p>
    <p class="status-line is-unavailable" id="device-transfer-status" style="display:none;"></p>
    <button class="primary-btn" type="button" id="qr-ok">OK</button>
  `;

  const qrEl = card.querySelector('#device-transfer-qr');
  const loginEl = card.querySelector('#device-transfer-login');
  const keysEl = card.querySelector('#device-transfer-keys');
  const statusEl = card.querySelector('#device-transfer-status');

  (async () => {
    try {
      if (!state.session.login || !state.session.storagePwdInMemory) {
        throw new Error('Нет активной сессии для чтения ключей');
      }
      const savedKeys = await loadEncryptedUserSecrets(state.session.login, state.session.storagePwdInMemory);
      const keys = {
        deviceKey: savedKeys.deviceKey || '',
        blockchainKey: state.deviceConnect.blockchain ? (savedKeys.blockchainKey || '') : '',
        rootKey: state.deviceConnect.root ? (savedKeys.rootKey || '') : '',
      };
      if (!keys.deviceKey) throw new Error('На этом устройстве нет device key');

      const qrText = makeKeyTransferText({ login: state.session.login, keys });
      qrEl.innerHTML = renderQrSvg(qrText);
      loginEl.textContent = `Логин: ${state.session.login}`;
      keysEl.textContent = `Ключи: ${describeTransferKeys(keys).join(', ')}`;
    } catch (error) {
      qrEl.textContent = '';
      loginEl.textContent = 'Логин: нет данных';
      keysEl.textContent = 'Ключи: нет данных';
      statusEl.textContent = error?.message || 'Не удалось подготовить QR-код.';
      statusEl.style.display = '';
    }
  })();

  card.querySelector('#qr-ok').addEventListener('click', () => navigate('connect-device-view'));

  screen.append(card);
  return screen;
}
