package com.icing.dialer.services

import android.telecom.Call
import android.telecom.InCallService
import android.util.Log
import io.flutter.plugin.common.MethodChannel

class MyInCallService : InCallService() {
    companion object {
        var channel: MethodChannel? = null
        var currentCall: Call? = null
        private const val TAG = "MyInCallService"
    }

    private val callCallback = object : Call.Callback() {
        override fun onStateChanged(call: Call, state: Int) {
            super.onStateChanged(call, state)
            val stateStr = when (state) {
                Call.STATE_DIALING -> "dialing"
                Call.STATE_ACTIVE -> "active"
                Call.STATE_DISCONNECTED -> "disconnected"
                Call.STATE_DISCONNECTING -> "disconnecting"
                Call.STATE_RINGING -> "ringing"
                else -> "unknown"
            }
            Log.d(TAG, "State changed: $stateStr for call ${call.details.handle}")
            channel?.invokeMethod("callStateChanged", mapOf(
                "callId" to call.details.handle.toString(),
                "state" to stateStr
            ))
            if (state == Call.STATE_DISCONNECTED || state == Call.STATE_DISCONNECTING) {
                Log.d(TAG, "Call ended: ${call.details.handle}")
                channel?.invokeMethod("callEnded", mapOf("callId" to call.details.handle.toString()))
                currentCall = null
            }
        }
    }

    override fun onCallAdded(call: Call) {
        super.onCallAdded(call)
        currentCall = call
        val stateStr = when (call.state) {
            Call.STATE_DIALING -> "dialing"
            Call.STATE_ACTIVE -> "active"
            Call.STATE_RINGING -> "ringing"
            else -> "dialing" // Default for outgoing
        }
        Log.d(TAG, "Call added: ${call.details.handle}, state: $stateStr")
        channel?.invokeMethod("callAdded", mapOf(
            "callId" to call.details.handle.toString(),
            "state" to stateStr
        ))
        call.registerCallback(callCallback)
    }

    override fun onCallRemoved(call: Call) {
        super.onCallRemoved(call)
        Log.d(TAG, "Call removed: ${call.details.handle}")
        call.unregisterCallback(callCallback)
        channel?.invokeMethod("callRemoved", mapOf("callId" to call.details.handle.toString()))
        currentCall = null
    }

    override fun onCallAudioStateChanged(state: android.telecom.CallAudioState) {
        super.onCallAudioStateChanged(state)
        Log.d(TAG, "Audio state changed: route=${state.route}")
        channel?.invokeMethod("audioStateChanged", mapOf("route" to state.route))
    }
}