import { BackgroundMessage, MessageType } from '../types';

const apiUrlInput = document.getElementById('api-url') as HTMLInputElement;
const authTokenInput = document.getElementById('auth-token') as HTMLInputElement;
const enabledCheckbox = document.getElementById('enabled') as HTMLInputElement;
const activeBlockingCheckbox = document.getElementById('active-blocking') as HTMLInputElement;
const darkwatchCheckbox = document.getElementById('darkwatch-enabled') as HTMLInputElement;
const spamCheckbox = document.getElementById('spam-enabled') as HTMLInputElement;
const notificationsCheckbox = document.getElementById('notifications') as HTMLInputElement;
const blockedDomainsList = document.getElementById('blocked-domains') as HTMLElement;
const allowedDomainsList = document.getElementById('allowed-domains') as HTMLElement;
const newBlockedInput = document.getElementById('new-blocked-domain') as HTMLInputElement;
const newAllowedInput = document.getElementById('new-allowed-domain') as HTMLInputElement;
const saveBtn = document.getElementById('save-btn') as HTMLButtonElement;
const resetBtn = document.getElementById('reset-btn') as HTMLButtonElement;
const toast = document.getElementById('toast') as HTMLElement;

loadSettings();

function loadSettings(): void {
  chrome.runtime.sendMessage({ type: MessageType.GET_SETTINGS }, (response) => {
    const settings = (response as { settings: Record<string, unknown> }).settings;
    if (!settings) return;

    apiUrlInput.value = settings.apiBaseUrl || 'https://api.shieldai.com';
    authTokenInput.value = settings.authToken || '';
    enabledCheckbox.checked = settings.enabled !== false;
    activeBlockingCheckbox.checked = !!settings.activeBlocking;
    darkwatchCheckbox.checked = !!settings.darkWatchEnabled;
    spamCheckbox.checked = settings.spamProtectionEnabled !== false;
    notificationsCheckbox.checked = settings.showNotifications !== false;

    renderDomainList(blockedDomainsList, (settings.blockedDomains || []) as string[], 'blocked');
    renderDomainList(allowedDomainsList, (settings.allowedDomains || []) as string[], 'allowed');
  });
}

function renderDomainList(container: HTMLElement, domains: string[], type: string): void {
  container.innerHTML = domains.map((d, i) => `
    <li class="domain-item">
      <span>${d}</span>
      <button class="domain-remove" data-type="${type}" data-index="${i}">✕</button>
    </li>
  `).join('');
}

saveBtn.addEventListener('click', () => {
  chrome.runtime.sendMessage({
    type: MessageType.UPDATE_SETTINGS,
    payload: {
      apiBaseUrl: apiUrlInput.value,
      authToken: authTokenInput.value || null,
      enabled: enabledCheckbox.checked,
      activeBlocking: activeBlockingCheckbox.checked,
      darkWatchEnabled: darkwatchCheckbox.checked,
      spamProtectionEnabled: spamCheckbox.checked,
      showNotifications: notificationsCheckbox.checked,
    },
  }, () => {
    showToast('Settings saved!');
  });
});

resetBtn.addEventListener('click', () => {
  chrome.storage.sync.set({ shieldaiSettings: null }, () => {
    chrome.runtime.sendMessage({ type: MessageType.GET_SETTINGS }, (response) => {
      loadSettings();
      showToast('Settings reset to defaults');
    });
  });
});

document.getElementById('add-blocked')?.addEventListener('click', () => {
  const domain = newBlockedInput.value.trim().toLowerCase();
  if (!domain) return;

  chrome.runtime.sendMessage({ type: MessageType.GET_SETTINGS }, (response) => {
    const settings = (response as { settings: Record<string, unknown> }).settings;
    const domains = [...(settings.blockedDomains || []), domain];
    chrome.runtime.sendMessage({
      type: MessageType.UPDATE_SETTINGS,
      payload: { blockedDomains: domains },
    }, () => {
      newBlockedInput.value = '';
      renderDomainList(blockedDomainsList, domains, 'blocked');
      showToast(`Added ${domain} to blocked list`);
    });
  });
});

document.getElementById('add-allowed')?.addEventListener('click', () => {
  const domain = newAllowedInput.value.trim().toLowerCase();
  if (!domain) return;

  chrome.runtime.sendMessage({ type: MessageType.GET_SETTINGS }, (response) => {
    const settings = (response as { settings: Record<string, unknown> }).settings;
    const domains = [...(settings.allowedDomains || []), domain];
    chrome.runtime.sendMessage({
      type: MessageType.UPDATE_SETTINGS,
      payload: { allowedDomains: domains },
    }, () => {
      newAllowedInput.value = '';
      renderDomainList(allowedDomainsList, domains, 'allowed');
      showToast(`Added ${domain} to allowed list`);
    });
  });
});

function showToast(message: string): void {
  toast.textContent = message;
  toast.classList.add('show');
  setTimeout(() => toast.classList.remove('show'), 3000);
}
