import {
    decryptFileWithDek,
    decryptPraxisFile,
    openDekWithPatientCode,
    zeroize,
} from './crypto';
import { restorePraxisPrivateKey } from './session';

function showFlash(label: 'success' | 'danger' | 'error' | 'warning' | 'info', message: string): void {
    const globalShowFlash = (window as Window & { showFlash?: (label: string, message: string) => void }).showFlash;
    if (typeof globalShowFlash === 'function') {
        globalShowFlash(label === 'error' ? 'danger' : label, message);
        return;
    }

    const flashContainer = document.getElementById('flash-messages');
    if (!flashContainer) {
        console.error(message);
        return;
    }

    const flashElement = document.createElement('div');
    flashElement.className = `flash-message flash-message--${label === 'error' ? 'danger' : label}`;
    flashElement.innerHTML = `
        <div class="flash-message__icon">×</div>
        <div class="flash-message__text">
            <div class="headline">${(window as any).getFlashHeadline?.('danger') ?? 'Hinweis'}</div>
            <div class="subtext"></div>
        </div>
        <button class="flash-message__close" aria-label="Close">&times;</button>
    `;
    const subtext = flashElement.querySelector('.subtext');
    if (subtext) {
        subtext.textContent = message;
    }
    flashContainer.appendChild(flashElement);
    flashElement.querySelector('.flash-message__close')?.addEventListener('click', () => flashElement.remove());
    setTimeout(() => flashElement.remove(), 5000);
}

function flashMessage(key: 'needCode' | 'noPackage' | 'decryptFailed' | 'sessionFailed', fallback: string): string {
    const el = document.getElementById('praxis-download-flash');
    if (!el) {
        return fallback;
    }
    const attr = {
        needCode: 'data-need-code',
        noPackage: 'data-no-package',
        decryptFailed: 'data-decrypt-failed',
        sessionFailed: 'data-session-failed',
    }[key];
    return el.getAttribute(attr) || fallback;
}

function triggerBlobDownload(blob: Blob, fileName: string): void {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
}

function getPatientCodeFromDownloadPage(): string {
    const input = document.getElementById('praxis_patient_code_download') as HTMLInputElement | null;
    return (input?.value || '').trim();
}

async function downloadPraxisFile(fileId: number, fileName: string): Promise<void> {
    const metaRes = await fetch(`/api/praxis/file/${fileId}/download-meta`, {
        headers: { Accept: 'application/json' },
        credentials: 'same-origin',
    });
    const meta = await metaRes.json();
    if (!metaRes.ok) {
        throw new Error(meta.error || 'meta_failed');
    }

    const cipherRes = await fetch(`/api/praxis/file/${fileId}/ciphertext`, {
        credentials: 'same-origin',
    });
    if (!cipherRes.ok) {
        throw new Error('ciphertext_failed');
    }
    const cipherBlob = await cipherRes.blob();

    const praxisKey = await restorePraxisPrivateKey();
    if (!praxisKey) {
        throw new Error('praxis_key_unavailable');
    }
    try {
        const plain = await decryptPraxisFile(cipherBlob, meta.praxisSealedDek, praxisKey);
        triggerBlobDownload(plain, fileName.replace(/\.(enc|bin)$/i, '') || fileName);
    } finally {
        zeroize(praxisKey);
    }
}

document.addEventListener('click', (event) => {
    const target = event.target as HTMLElement | null;

    const patientLink = target?.closest('[data-praxis-patient-download]') as HTMLElement | null;
    if (patientLink) {
        event.preventDefault();
        const downloadUrl = patientLink.getAttribute('data-download-url') || '';
        const fileName = patientLink.getAttribute('data-file-name') || 'download.bin';
        const sealed = patientLink.getAttribute('data-patient-sealed-dek') || '';
        if (!sealed) {
            showFlash('danger', flashMessage('noPackage', 'No patient code package is available for this file.'));
            return;
        }
        const code = getPatientCodeFromDownloadPage();
        if (code.length < 12) {
            const input = document.getElementById('praxis_patient_code_download') as HTMLInputElement | null;
            input?.focus();
            showFlash(
                'danger',
                flashMessage('needCode', 'Please enter the code from your practice (at least 12 characters).'),
            );
            return;
        }
        void (async () => {
            const cipherRes = await fetch(downloadUrl, { credentials: 'same-origin' });
            if (!cipherRes.ok) {
                throw new Error('ciphertext_failed');
            }
            const cipherBlob = await cipherRes.blob();
            const dek = openDekWithPatientCode(sealed, code);
            try {
                const plain = await decryptFileWithDek(cipherBlob, dek);
                triggerBlobDownload(plain, fileName);
            } finally {
                zeroize(dek);
            }
        })().catch((err) => {
            console.error(err);
            showFlash(
                'danger',
                flashMessage('decryptFailed', 'Decryption failed. Check the code and try again.'),
            );
        });
        return;
    }

    const link = target?.closest('[data-praxis-download]') as HTMLElement | null;
    if (!link) {
        return;
    }
    event.preventDefault();
    const fileId = Number(link.getAttribute('data-file-id') || '0');
    const fileName = link.getAttribute('data-file-name') || 'download.bin';
    void downloadPraxisFile(fileId, fileName).catch((err) => {
        console.error(err);
        showFlash(
            'danger',
            flashMessage('sessionFailed', 'Download / decryption failed. Please sign in again with your password.'),
        );
    });
});
