import './settings.scss';
import {
    b64encode,
    createPraxisKey,
    derivePasswordMaterial,
    encryptWithKey,
    wrapHalfBAtKek,
    zeroize,
} from './crypto';

function csrfToken(): string {
    const el = document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null;
    return el?.content || '';
}

async function enablePraxisEncryption(): Promise<void> {
    const passwordInput = document.getElementById('praxis_enable_password') as HTMLInputElement | null;
    const statusEl = document.getElementById('praxis_enable_status');
    const button = document.getElementById('praxis_enable_btn') as HTMLButtonElement | null;
    if (!passwordInput || !button) {
        return;
    }

    const password = passwordInput.value;
    if (password.length < 8) {
        if (statusEl) {
            statusEl.textContent = statusEl.dataset.needPassword || 'Password required (min. 8 characters).';
        }
        return;
    }

    button.disabled = true;
    if (statusEl) {
        statusEl.textContent = statusEl.dataset.working || 'Working…';
    }

    let halfA: Uint8Array | null = null;
    let halfB: Uint8Array | null = null;
    let praxisKey: Uint8Array | null = null;
    let fileKey: Uint8Array | null = null;

    try {
        const provisionRes = await fetch('/api/praxis/provision', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
            credentials: 'same-origin',
        });
        let provision: any;
        try {
            provision = await provisionRes.json();
        } catch {
            throw new Error(`provision_failed_http_${provisionRes.status}`);
        }
        if (!provisionRes.ok) {
            const detail = provision.message || provision.error || `HTTP ${provisionRes.status}`;
            throw new Error(`KEK-Anlage fehlgeschlagen: ${detail}`);
        }

        const derived = await derivePasswordMaterial(password);
        fileKey = derived.fileKey;

        const bundle = createPraxisKey();
        praxisKey = bundle.praxisKey;
        halfA = bundle.halfA;
        halfB = bundle.halfB;

        let wrappedHalfB: string;
        try {
            wrappedHalfB = await wrapHalfBAtKek(
                provision.kekBaseUrl,
                provision.publicId,
                provision.secret,
                halfB,
                provision.keyVersion,
            );
        } catch (wrapErr) {
            const msg = wrapErr instanceof Error ? wrapErr.message : String(wrapErr);
            throw new Error(
                `KEK-Wrap fehlgeschlagen (oft CORS von localhost): ${msg}. `
                + 'KEK muss Origin http://localhost:8000 erlauben.',
            );
        }

        const encryptedHalfA = encryptWithKey(fileKey, halfA);
        const encryptedKekSecret = encryptWithKey(fileKey, new TextEncoder().encode(provision.secret));

        const enableRes = await fetch('/api/praxis/enable', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
            credentials: 'same-origin',
            body: JSON.stringify({
                publicKey: bundle.publicKeyB64,
                encryptedHalfA,
                wrappedHalfB,
                kekKeyVersion: provision.keyVersion,
                kekPublicId: provision.publicId,
                encryptedKekSecret,
                passwordSalt: derived.saltB64,
                loginVerifier: derived.loginVerifier,
            }),
        });
        let enableData: any;
        try {
            enableData = await enableRes.json();
        } catch {
            throw new Error(`enable_failed_http_${enableRes.status}`);
        }
        if (!enableRes.ok) {
            throw new Error(enableData.error || `enable_failed_http_${enableRes.status}`);
        }

        sessionStorage.setItem('sft_praxis_file_key', b64encode(fileKey));
        sessionStorage.setItem('sft_praxis_enabled', '1');

        if (statusEl) {
            statusEl.textContent = statusEl.dataset.done || 'Password encryption enabled.';
        }
        window.location.reload();
    } catch (e) {
        console.error(e);
        if (statusEl) {
            const detail = e instanceof Error ? e.message : String(e);
            statusEl.textContent = `${statusEl.dataset.failed || 'Aktivierung fehlgeschlagen.'} (${detail})`;
        }
        button.disabled = false;
    } finally {
        if (halfA) zeroize(halfA);
        if (halfB) zeroize(halfB);
        if (praxisKey) zeroize(praxisKey);
        if (fileKey) zeroize(fileKey);
        passwordInput.value = '';
        passwordInput.type = 'password';
        const toggleBtn = document.getElementById('praxis_enable_password_toggle') as HTMLButtonElement | null;
        if (toggleBtn) {
            toggleBtn.hidden = true;
            const icon = toggleBtn.querySelector('i');
            if (icon) {
                icon.className = 'icofont-eye';
            }
        }
    }
}

function syncPasswordToggleVisibility(): void {
    const passwordInput = document.getElementById('praxis_enable_password') as HTMLInputElement | null;
    const toggleBtn = document.getElementById('praxis_enable_password_toggle') as HTMLButtonElement | null;
    if (!passwordInput || !toggleBtn) {
        return;
    }
    // Show eye only once the field has content (otherwise meaningless).
    toggleBtn.hidden = passwordInput.value.length === 0;
    if (toggleBtn.hidden) {
        passwordInput.type = 'password';
        const icon = toggleBtn.querySelector('i');
        if (icon) {
            icon.className = 'icofont-eye';
        }
        toggleBtn.setAttribute('aria-label', toggleBtn.dataset.labelShow || 'Show password');
    }
}

document.addEventListener('DOMContentLoaded', () => {
    const button = document.getElementById('praxis_enable_btn');
    button?.addEventListener('click', (event) => {
        event.preventDefault();
        void enablePraxisEncryption();
    });

    const passwordInput = document.getElementById('praxis_enable_password') as HTMLInputElement | null;
    const toggleBtn = document.getElementById('praxis_enable_password_toggle') as HTMLButtonElement | null;

    passwordInput?.addEventListener('input', syncPasswordToggleVisibility);
    passwordInput?.addEventListener('focus', syncPasswordToggleVisibility);
    syncPasswordToggleVisibility();

    toggleBtn?.addEventListener('click', () => {
        if (!passwordInput || !toggleBtn || toggleBtn.hidden) {
            return;
        }
        const show = passwordInput.type === 'password';
        passwordInput.type = show ? 'text' : 'password';
        const icon = toggleBtn.querySelector('i');
        if (icon) {
            icon.className = show ? 'icofont-eye-blocked' : 'icofont-eye';
        }
        toggleBtn.setAttribute(
            'aria-label',
            show
                ? (toggleBtn.dataset.labelHide || 'Hide password')
                : (toggleBtn.dataset.labelShow || 'Show password'),
        );
        passwordInput.focus();
    });
});

void csrfToken;
