import { SIPClient } from '@/lib/sip-client';
import type { SIPConfig, ConnectionStatus, CallState } from '@/types/sip';

// Singleton SIP client — survives React StrictMode remounts
let sipClient: SIPClient | null = null;
let connected = false;
let outboundPending = false;
let outboundActive = false;

type StateUpdater = {
    setConnectionStatus: (status: ConnectionStatus) => void;
    setCallState: (state: CallState) => void;
    setCallerNumber: (number: string | null) => void;
    setCallUcid: (ucid: string | null) => void;
};

let stateUpdater: StateUpdater | null = null;

export function registerSipStateUpdater(updater: StateUpdater) {
    stateUpdater = updater;
}

export function setOutboundPending(pending: boolean) {
    outboundPending = pending;
}

export function isOutboundPending(): boolean {
    return outboundPending;
}

export function connectSip(config: SIPConfig): void {
    if (connected || sipClient?.isRegistered() || sipClient?.isConnected()) {
        return;
    }

    if (!config.wsServer || !config.uri) {
        console.warn('SIP config incomplete — wsServer and uri required');
        return;
    }

    if (sipClient) {
        sipClient.disconnect();
    }

    connected = true;
    stateUpdater?.setConnectionStatus('connecting');

    sipClient = new SIPClient(
        config,
        (status) => stateUpdater?.setConnectionStatus(status),
        (state, number, ucid) => {
            // Auto-answer SIP when it's a bridge from our outbound call
            if (state === 'ringing-in' && outboundPending) {
                outboundPending = false;
                outboundActive = true;
                console.log('[SIP-MGR] Outbound bridge detected — auto-answering');
                setTimeout(() => {
                    sipClient?.answer();
                    setTimeout(() => stateUpdater?.setCallState('active'), 300);
                }, 500);
                if (ucid) stateUpdater?.setCallUcid(ucid);
                return;
            }

            console.log(`[SIP-MGR] State: ${state} | caller=${number ?? 'none'} | ucid=${ucid ?? 'none'} | outboundActive=${outboundActive}`);

            stateUpdater?.setCallState(state);
            if (!outboundActive && number !== undefined) {
                stateUpdater?.setCallerNumber(number ?? null);
            }

            if (ucid) stateUpdater?.setCallUcid(ucid);

            if (state === 'ended' || state === 'failed') {
                outboundActive = false;
                outboundPending = false;
            }
        },
    );

    sipClient.connect();
}

export function disconnectSip(): void {
    console.log('[SIP-MGR] Disconnecting SIP');
    sipClient?.disconnect();
    sipClient = null;
    connected = false;
    outboundPending = false;
    outboundActive = false;
    stateUpdater?.setConnectionStatus('disconnected');
    stateUpdater?.setCallUcid(null);
}

export function getSipClient(): SIPClient | null {
    return sipClient;
}
