/**
 * Tracking page logic
 */

import { getAllEntries, getTrackingSummary, clearTracking, exportAsCSV } from './tracker';

// DOM Elements
const totalTransfersEl = document.getElementById('totalTransfers')!;
const successfulTransfersEl = document.getElementById('successfulTransfers')!;
const failedTransfersEl = document.getElementById('failedTransfers')!;
const lastTransferEl = document.getElementById('lastTransfer')!;

const emptyState = document.getElementById('emptyState')!;
const historyList = document.getElementById('historyList')!;

const exportBtn = document.getElementById('exportBtn')!;
const clearBtn = document.getElementById('clearBtn')!;

/**
 * Initialize tracking page
 */
async function init() {
  await loadSummary();
  await loadHistory();

  // Setup event listeners
  exportBtn.addEventListener('click', handleExport);
  clearBtn.addEventListener('click', handleClear);
}

/**
 * Load summary statistics
 */
async function loadSummary() {
  const summary = await getTrackingSummary();

  totalTransfersEl.textContent = summary.totalTransfers.toString();
  successfulTransfersEl.textContent = summary.successfulTransfers.toString();
  failedTransfersEl.textContent = summary.failedTransfers.toString();

  if (summary.lastTransferTime) {
    lastTransferEl.textContent = `Last transfer: ${formatDate(summary.lastTransferTime)}`;
  } else {
    lastTransferEl.textContent = 'No transfers yet';
  }
}

/**
 * Load transfer history
 */
async function loadHistory() {
  const entries = await getAllEntries();

  if (entries.length === 0) {
    emptyState.style.display = 'block';
    historyList.style.display = 'none';
    (exportBtn as HTMLButtonElement).disabled = true;
    (clearBtn as HTMLButtonElement).disabled = true;
    return;
  }

  emptyState.style.display = 'none';
  historyList.style.display = 'flex';
  (exportBtn as HTMLButtonElement).disabled = false;
  (clearBtn as HTMLButtonElement).disabled = false;

  // Render history items
  historyList.innerHTML = '';
  entries.forEach((entry) => {
    const item = document.createElement('div');
    item.className = `history-item ${entry.result}`;

    const info = document.createElement('div');
    info.className = 'history-info';

    const domain = document.createElement('div');
    domain.className = 'history-domain';
    domain.textContent = entry.sourceDomain;

    const meta = document.createElement('div');
    meta.className = 'history-meta';
    meta.textContent = `${formatFileSize(entry.pdfSize)} • ${entry.destinationUrl}`;

    info.appendChild(domain);
    info.appendChild(meta);

    if (entry.errorMessage) {
      const error = document.createElement('div');
      error.className = 'history-error';
      error.textContent = entry.errorMessage;
      info.appendChild(error);
    }

    const status = document.createElement('div');
    status.className = 'history-status';

    const result = document.createElement('div');
    result.className = `history-result ${entry.result}`;
    result.textContent = entry.result;

    const timestamp = document.createElement('div');
    timestamp.className = 'history-timestamp';
    timestamp.textContent = formatDate(entry.timestamp);

    status.appendChild(result);
    status.appendChild(timestamp);

    item.appendChild(info);
    item.appendChild(status);

    historyList.appendChild(item);
  });
}

/**
 * Handle export to CSV
 */
async function handleExport() {
  const entries = await getAllEntries();
  const csv = exportAsCSV(entries);

  // Copy to clipboard
  try {
    await navigator.clipboard.writeText(csv);

    // Also open email with CSV
    const subject = encodeURIComponent('BinectChrome Transfer History');
    const body = encodeURIComponent(
      `Please find my BinectChrome transfer history below:\n\n${csv}`
    );
    const mailtoUrl = `mailto:bernd.worsch@binect.de?subject=${subject}&body=${body}`;

    window.open(mailtoUrl);

    alert('CSV copied to clipboard and email draft opened!');
  } catch (error) {
    // Fallback: download CSV file
    downloadCSV(csv, 'binect-chrome-history.csv');
    alert('CSV file downloaded!');
  }
}

/**
 * Download CSV file
 */
function downloadCSV(csv: string, filename: string) {
  const blob = new Blob([csv], { type: 'text/csv' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

/**
 * Handle clear history
 */
async function handleClear() {
  if (
    !confirm(
      'Are you sure you want to clear all transfer history? This cannot be undone.'
    )
  ) {
    return;
  }

  await clearTracking();
  await loadSummary();
  await loadHistory();
}

/**
 * Format file size
 */
function formatFileSize(bytes: number): string {
  if (bytes < 1024) {
    return `${bytes} B`;
  } else if (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  } else {
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  }
}

/**
 * Format date
 */
function formatDate(timestamp: number): string {
  const date = new Date(timestamp);
  return date.toLocaleString();
}

// Initialize on load
init();
