import '@/arx-icons';
import '@components/Breadcrumbs';
import '@components/ErrorView';
import '@components/Header';
import '@components/LoadingView';
import '@components/NostrAvatar';
import '@components/NostrProfile';
import '@routes/router';
import type EveRouter from '@routes/router';
import './style.css';

let availableCCNs: { name: string; pubkey: string }[] = [];

function checkRelayUp() {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      ws.close();
      reject(new Error('Connection timeout'));
    }, 5000);

    const ws = new WebSocket('ws://localhost:6942');

    ws.onopen = () => {
      clearTimeout(timeoutId);
      ws.send(JSON.stringify(['CCN', 'LIST']));
    };

    ws.onmessage = async (message) => {
      const data = JSON.parse(message.data);
      console.log(data);
      if (data[0] !== 'OK' || data[1] !== 'CCN LIST' || data[2] !== true) return;
      availableCCNs = JSON.parse(data[3]);
      if (availableCCNs.length === 0) throw new Error('No CCNs found');
      if (availableCCNs.length === 1) {
        ws.send(
          JSON.stringify([
            'CCN',
            'ACTIVATE',
            {
              pubkey: availableCCNs[0].pubkey,
            },
          ]),
        );
        return resolve(true);
      }
      if (localStorage.getItem('selectedCCN')) {
        const selected = JSON.parse(localStorage.getItem('selectedCCN')!) as { date: number; pubkey: string };
        if (Date.now() - selected.date < 1000 * 60 * 60 * 24) {
          ws.send(JSON.stringify(['CCN', 'ACTIVATE', { pubkey: selected.pubkey }]));
          return resolve(true);
        }
      }
      await new Promise((resolve) => {
        let selectedCCN: string | null = availableCCNs[0].pubkey;
        const selectBox = document.createElement('arx-select');
        selectBox.options = availableCCNs.map((ccn) => ({ label: ccn.name, value: ccn.pubkey }));
        selectBox.addEventListener('change', (e) => {
          selectedCCN = e.target.value;
        });
        const okButton = document.createElement('arx-button');
        okButton.label = 'OK';
        okButton.addEventListener('click', () => {
          if (selectedCCN) {
            ws.send(
              JSON.stringify([
                'CCN',
                'ACTIVATE',
                {
                  pubkey: selectedCCN,
                },
              ]),
            );
            localStorage.setItem('selectedCCN', JSON.stringify({ date: Date.now(), pubkey: selectedCCN }));
            resolve(true);
            document.body.removeChild(dialog);
          }
        });
        const dialog = document.createElement('arx-dialog');
        dialog.title = 'Select CCN';
        dialog.open = true;
        dialog.appendChild(selectBox);
        dialog.appendChild(okButton);
        document.body.appendChild(dialog);
      });
      resolve(true);
    };

    ws.onerror = (error) => {
      clearTimeout(timeoutId);
      reject(error);
    };
  });
}

async function startRelay() {
  if (localStorage.getItem('ncryptsec')) {
    const loadingIndicator = document.createElement('arx-loading-view');
    document.body.appendChild(loadingIndicator);
    await window.relay.start(localStorage.getItem('encryption_key')!);
    try {
      await checkRelayUp();
    } catch (err) {
      alert('Could not connect to relay. This might be because the relay is not running. Try restarting Eve');
    }
    loadingIndicator.remove();
  }
}

if (localStorage.getItem('darkMode') === 'true') document.body.classList.add('dark');

startRelay().then(() => {
  const router = document.createElement('arx-eve-router') as EveRouter;
  router.ccnSetup = !!localStorage.getItem('ncryptsec');
  document.body.appendChild(router);
});
