import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { LoadingIndicator } from '../../UI/loading/LoadingIndicator';
import { AmbientAlert } from '../../UI/feedback/AmbientAlert';
import { ConfigService } from '../../configService';
import { exchangeAuthorizationCode, getOutlookRedirectUri, } from './outlookIntegrationClient';
import { refreshOutlookStatus } from './outlookIntegrationStatus';
export const OutlookIntegrationCallbackPage = () => {
    const location = useLocation();
    const [error, setError] = useState(null);
    const [debugLog, setDebugLog] = useState([]);
    const debugEnabled = isDebugEnabled();
    const { code, state, errorParam, errorDescription } = useMemo(() => {
        const params = new URLSearchParams(location.search);
        return {
            code: params.get('code'),
            state: params.get('state'),
            errorParam: params.get('error'),
            errorDescription: params.get('error_description'),
        };
    }, [location.search]);
    const redirectUri = useMemo(() => getOutlookRedirectUri(), []);
    const log = useCallback(message => {
        const timestamp = new Date().toISOString();
        console.debug(`[OutlookCallback] ${message}`);
        if (!debugEnabled)
            return;
        setDebugLog(prev => [...prev, `${timestamp} ${message}`]);
    }, [debugEnabled]);
    const closePopup = useCallback(() => {
        if (debugEnabled) {
            log('Debug mode enabled; window will remain open for inspection.');
            return;
        }
        log('Closing Outlook popup after successful authorization.');
        closeWindowSoon();
    }, [debugEnabled, log]);
    useEffect(() => {
        log(`Callback page mounted with search: "${location.search || '<empty>'}"`);
        if (errorParam) {
            const message = errorDescription || errorParam || 'Outlook authorization failed.';
            log(`Outlook authorization returned error: ${message}`);
            setError(message);
            notifyParent('outlookConnectFailure', message);
            return;
        }
        if (!code || !state) {
            const message = 'Authorization details missing from Outlook redirect.';
            log('Authorization code or state missing in query string.');
            setError(message);
            notifyParent('outlookConnectFailure', message);
            return;
        }
        log(`Exchanging authorization code via redirect URI: ${redirectUri}`);
        exchangeAuthorizationCode({ authorizationCode: code, state, redirectUri })
            .then(() => {
            log('Authorization code exchange succeeded; refreshing Outlook status.');
            return refreshOutlookStatus();
        })
            .then(() => {
            log('Outlook status refreshed; notifying parent of success.');
            notifyParent('outlookConnectSuccess');
            closePopup();
        })
            .catch(err => {
            const message = extractErrorMessage(err, 'Failed to finalize the Outlook connection.');
            log(`Outlook connect flow failed: ${message}`);
            setError(message);
            notifyParent('outlookConnectFailure', message);
            log('Leaving callback window open so the error details stay visible.');
        });
    }, [
        closePopup,
        code,
        errorDescription,
        errorParam,
        location.search,
        log,
        redirectUri,
        state,
    ]);
    return (React.createElement(React.Fragment, null, !error && React.createElement(LoadingIndicator, null), error && (React.createElement(AmbientAlert, { alertSeverity: "error", showAlert: true, alertMessage: error })), debugEnabled && (React.createElement("div", { style: {
            marginTop: 16,
            padding: '12px 14px',
            backgroundColor: '#111',
            color: '#eee',
            borderRadius: 4,
            fontFamily: 'monospace',
            fontSize: 12,
            maxHeight: '40vh',
            overflowY: 'auto',
        } }, React.createElement("strong", { style: { display: 'block', marginBottom: 8 } }, "Outlook callback debug lo"), debugLog.length === 0 ? (React.createElement("div", null, "Waiting for events...")) : (debugLog.map((entry, idx) => React.createElement("div", { key: idx }, entry))), React.createElement("div", { style: { marginTop: 12 } }, "This window will stay open in debug mode. Close it manually afte reviewing the log")))));
};
function notifyParent(type, message) {
    var _a, _b;
    try {
        (_a = window.opener) === null || _a === void 0 ? void 0 : _a.postMessage({ type, message }, window.location.origin);
    }
    catch (_c) {
        // ignore
    }
    try {
        (_b = window.opener) === null || _b === void 0 ? void 0 : _b.postMessage(type, window.location.origin);
    }
    catch (_d) {
        // ignore
    }
}
function closeWindowSoon() {
    setTimeout(() => {
        try {
            window.close();
        }
        catch (_a) {
            // ignore
        }
    }, 750);
}
function extractErrorMessage(error, fallback) {
    var _a, _b;
    if (!error)
        return fallback;
    if (typeof error === 'string')
        return error;
    if (typeof error.message === 'string' && error.message.trim()) {
        return error.message;
    }
    const responseMessage = ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) || ((_b = error === null || error === void 0 ? void 0 : error.response) === null || _b === void 0 ? void 0 : _b.statusText) || (error === null || error === void 0 ? void 0 : error.message);
    if (typeof responseMessage === 'string' && responseMessage.trim()) {
        return responseMessage;
    }
    return fallback;
}
export default OutlookIntegrationCallbackPage;
function isDebugEnabled() {
    var _a;
    const raw = (_a = ConfigService === null || ConfigService === void 0 ? void 0 : ConfigService.config) === null || _a === void 0 ? void 0 : _a.OUTLOOK_POPUP_DEBUG;
    if (typeof raw === 'boolean') {
        return raw;
    }
    return String(raw !== null && raw !== void 0 ? raw : '').toLowerCase() === 'true';
}
//# sourceMappingURL=OutlookIntegrationCallbackPage.js.map