import { navigate } from '../router.js';
import { isLoggedIn, showToast } from '../app.js';
import { apiGet, invalidateSessionCheck, apiUrl } from '../api.js';

const WEBSITE_ROLES = ['admin', 'supervisor'];

function setFormBusy(formId, busy, busyLabel) {
    const form = document.getElementById(formId);
    if (!form) return;
    const btn = form.querySelector('button[type="submit"]');
    if (!btn) return;
    if (!btn.dataset.defaultLabel) {
        btn.dataset.defaultLabel = btn.textContent.trim();
    }
    btn.disabled = busy;
    btn.textContent = busy ? busyLabel : btn.dataset.defaultLabel;
    form.querySelectorAll('input').forEach((el) => { el.disabled = busy; });
}

function setButtonBusy(button, busy, busyLabel) {
    if (!button) return;
    if (!button.dataset.defaultLabel) {
        button.dataset.defaultLabel = button.textContent.trim();
    }
    button.disabled = busy;
    button.textContent = busy ? busyLabel : button.dataset.defaultLabel;
}

export async function loginPage() {
    if (isLoggedIn()) {
        try {
            const data = await apiGet('session');
            if (data.success && data.valid && !data.mustChangePassword && WEBSITE_ROLES.includes(data.role)) {
                if (data.user) localStorage.setItem('qdb_user', data.user);
                if (data.role) localStorage.setItem('qdb_role', data.role);
                navigate('#/');
                return;
            }
        } catch {
            invalidateSessionCheck();
        }
        localStorage.removeItem('qdb_token');
        localStorage.removeItem('qdb_user');
        localStorage.removeItem('qdb_role');
        invalidateSessionCheck();
    }

    const app = document.getElementById('app');
    app.innerHTML = `
        <div class="login-screen" role="main">
            <div class="login-screen__backdrop" aria-hidden="true">
                <div class="login-grid"></div>
            </div>

            <div class="login-screen__content">
                <header class="login-brand">
                    <h1 class="login-brand__title">BW Sch&uuml;tzt - NAT-AS</h1>
                    <p class="login-brand__subtitle">Questionnaire Management</p>
                </header>

                <div id="loginOptions" class="login-options">
                    <section class="login-card login-card--local card" aria-labelledby="login-panel-title">
                        <h2 id="login-panel-title" class="login-card__heading">Local account</h2>
                        <p id="loginPanelSubtitle" class="login-card__lead">Admin or supervisor account.</p>

                        <form id="loginForm" class="login-form" autocomplete="on">
                            <div class="form-group">
                                <label for="username">Username</label>
                                <input type="text" id="username" name="username" autocomplete="username" required>
                            </div>
                            <div class="form-group">
                                <label for="password">Password</label>
                                <input type="password" id="password" name="password" autocomplete="current-password" required>
                            </div>
                            <button type="submit" class="btn btn-primary btn-block">Log in</button>
                            <p id="loginError" class="login-alert login-alert--error" role="alert" hidden></p>
                        </form>

                        <div id="changePwSection" class="login-change" hidden>
                            <hr>
                            <p>You must change your password before continuing.</p>
                            <form id="changePwForm" class="login-form">
                                <div class="form-group">
                                    <label for="newPw">New password</label>
                                    <input type="password" id="newPw" autocomplete="new-password" required minlength="6">
                                </div>
                                <div class="form-group">
                                    <label for="newPwConfirm">Confirm password</label>
                                    <input type="password" id="newPwConfirm" autocomplete="new-password" required minlength="6">
                                </div>
                                <button type="submit" class="btn btn-primary btn-block">Change and continue</button>
                                <p id="changePwError" class="login-alert login-alert--error" role="alert" hidden></p>
                            </form>
                        </div>
                    </section>

                    <section id="keycloakLoginSection" class="login-card login-card--sso card" aria-labelledby="keycloak-panel-title">
                        <h2 id="keycloak-panel-title" class="login-card__heading">University login</h2>
                        <p id="keycloakPanelSubtitle" class="login-card__lead">Use your University Konstanz credentials.</p>
                        <div class="login-sso">
                            <div class="login-sso__logo" aria-hidden="true">
                                <img
                                    src="media/uni-logo.png"
                                    alt=""
                                    onerror="this.hidden=true; this.parentElement.classList.add('login-sso__logo--fallback');"
                                >
                                <span>Universit&auml;t Konstanz</span>
                            </div>
                            <button id="keycloakLoginBtn" type="button" class="btn btn-block login-sso__button" disabled>
                                Log in with University Konstanz
                            </button>
                            <p id="keycloakLoginError" class="login-alert login-alert--error" role="alert" hidden></p>
                        </div>
                    </section>
                </div>

                <p class="login-card__footnote">Counselors use the mobile app.</p>
            </div>
        </div>
    `;

    let pendingUsername = '';
    let pendingTempToken = '';

    const keycloakSection = document.getElementById('keycloakLoginSection');
    const keycloakBtn = document.getElementById('keycloakLoginBtn');
    const keycloakErr = document.getElementById('keycloakLoginError');
    let keycloakLoginUrl = '';

    apiGet('auth/keycloak-config')
        .then((data) => {
            if (!data.success || !data.enabled) {
                keycloakBtn.textContent = 'University login unavailable';
                return;
            }
            keycloakLoginUrl = data.loginUrl ? apiUrl(data.loginUrl) : apiUrl('auth/keycloak-login');
            keycloakBtn.textContent = `Log in with ${data.displayName || 'University Konstanz'}`;
            keycloakBtn.disabled = false;
        })
        .catch(() => {
            keycloakBtn.textContent = 'University login unavailable';
        });

    keycloakBtn.addEventListener('click', () => {
        keycloakErr.hidden = true;
        if (!keycloakLoginUrl) {
            keycloakErr.textContent = 'University login is not available.';
            keycloakErr.hidden = false;
            return;
        }
        setButtonBusy(keycloakBtn, true, 'Redirecting...');
        window.location.assign(keycloakLoginUrl);
    });

    document.getElementById('loginForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const errEl = document.getElementById('loginError');
        errEl.hidden = true;
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;

        setFormBusy('loginForm', true, 'Signing in…');
        try {
            const res = await fetch(apiUrl('auth/login'), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-QDB-Client': 'web',
                },
                body: JSON.stringify({ username, password }),
            });
            const json = await res.json();
            if (!json.ok) {
                const code = json.error?.code || '';
                let msg = json.error?.message || 'Login failed';
                if (res.status === 429 || code === 'RATE_LIMITED') {
                    const retry = res.headers.get('Retry-After');
                    if (retry) {
                        msg += ` Try again in about ${retry} seconds.`;
                    }
                }
                errEl.textContent = msg;
                errEl.hidden = false;
                return;
            }
            const d = json.data;
            if (d.role === 'coach') {
                errEl.textContent = 'Counselor accounts can only sign in through the mobile app.';
                errEl.hidden = false;
                return;
            }
            if (d.mustChangePassword) {
                pendingUsername = username;
                pendingTempToken = d.token;
                document.getElementById('loginForm').hidden = true;
                document.getElementById('changePwSection').hidden = false;
                keycloakSection.hidden = true;
                document.getElementById('login-panel-title').textContent = 'New password';
                document.getElementById('loginPanelSubtitle').textContent = pendingUsername;
                document.getElementById('newPw').focus();
                return;
            }
            localStorage.setItem('qdb_token', d.token);
            localStorage.setItem('qdb_user', d.user);
            localStorage.setItem('qdb_role', d.role);
            invalidateSessionCheck();
            navigate('#/');
        } catch (err) {
            errEl.textContent = err.message;
            errEl.hidden = false;
        } finally {
            setFormBusy('loginForm', false, 'Signing in…');
        }
    });

    document.getElementById('changePwForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const errEl = document.getElementById('changePwError');
        errEl.hidden = true;
        const newPw = document.getElementById('newPw').value;
        const confirm = document.getElementById('newPwConfirm').value;
        if (newPw !== confirm) {
            errEl.textContent = 'Passwords do not match';
            errEl.hidden = false;
            return;
        }
        const oldPw = document.getElementById('password').value;

        setFormBusy('changePwForm', true, 'Saving…');
        try {
            const headers = {
                'Content-Type': 'application/json',
                'X-QDB-Client': 'web',
            };
            if (pendingTempToken) {
                headers['Authorization'] = `Bearer ${pendingTempToken}`;
            }
            const res = await fetch(apiUrl('auth/change-password'), {
                method: 'POST',
                headers,
                body: JSON.stringify({ username: pendingUsername, old_password: oldPw, new_password: newPw }),
            });
            const json = await res.json();
            if (!json.ok) {
                errEl.textContent = json.error?.message || 'Password change failed';
                errEl.hidden = false;
                return;
            }
            const d = json.data;
            if (d.role === 'coach') {
                errEl.textContent = 'Counselor accounts can only sign in through the mobile app.';
                errEl.hidden = false;
                return;
            }
            localStorage.setItem('qdb_token', d.token);
            localStorage.setItem('qdb_user', d.user);
            localStorage.setItem('qdb_role', d.role);
            invalidateSessionCheck();
            showToast('Password changed successfully', 'success');
            navigate('#/');
        } catch (err) {
            errEl.textContent = err.message;
            errEl.hidden = false;
        } finally {
            setFormBusy('changePwForm', false, 'Saving…');
        }
    });
}
