package com.humand.demo.modules.CallService

import android.app.Application
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import com.humand.demo.MainActivity
import com.humand.demo.R
import io.getstream.video.android.core.Call
import io.getstream.video.android.core.RingingState
import io.getstream.video.android.core.notifications.DefaultNotificationHandler
import io.getstream.video.android.model.StreamCallId

/**
 * Custom notification handler that:
 * - Ignores incoming/ringing notifications (handled by IncomingCallMessagingService)
 * - Provides ongoing call notifications that open MainActivity (not GetStream's default activity)
 */
@Suppress("DEPRECATION")
class CustomNotificationHandler(
    private val application: Application
) : DefaultNotificationHandler(
    application = application,
    hideRingingNotificationInForeground = true
) {

    companion object {
        private const val ONGOING_CALL_CHANNEL_ID = "ongoing_call_channel"
        private const val ONGOING_CALL_CHANNEL_NAME = "Ongoing Calls"
    }

    init {
        createOngoingCallChannel()
    }

    private fun createOngoingCallChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                ONGOING_CALL_CHANNEL_ID,
                ONGOING_CALL_CHANNEL_NAME,
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "Shows when you're in an active call"
                setShowBadge(false)
            }
            val notificationManager = application.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    override fun onRingingCall(callId: StreamCallId, callDisplayName: String) {
        callLog("CustomNotificationHandler: onRingingCall ignored for $callId - handled by IncomingCallMessagingService")
    }

    override fun getRingingCallNotification(
        ringingState: RingingState,
        callId: StreamCallId,
        callDisplayName: String?,
        shouldHaveContentIntent: Boolean
    ): Notification? {
        callLog("CustomNotificationHandler: getRingingCallNotification returning null for $callId")
        return null
    }

    override fun getIncomingCallNotification(
        fullScreenPendingIntent: PendingIntent,
        acceptCallPendingIntent: PendingIntent,
        rejectCallPendingIntent: PendingIntent,
        callerName: String?,
        shouldHaveContentIntent: Boolean
    ): Notification? {
        return null
    }

    override fun getOngoingCallNotification(
        callId: StreamCallId,
        callDisplayName: String?,
        isOutgoingCall: Boolean,
        remoteParticipantCount: Int
    ): Notification {
        callLog("CustomNotificationHandler: getOngoingCallNotification for $callId")
        return buildOngoingCallNotification(callDisplayName ?: "Call in progress")
    }

    override suspend fun onCallNotificationUpdate(call: Call): Notification? {
        callLog("CustomNotificationHandler: onCallNotificationUpdate")
        return buildOngoingCallNotification("Call in progress")
    }

    override suspend fun updateOngoingCallNotification(call: Call, callDisplayName: String): Notification? {
        callLog("CustomNotificationHandler: updateOngoingCallNotification")
        return buildOngoingCallNotification(callDisplayName)
    }

    override suspend fun updateOutgoingCallNotification(call: Call, callDisplayName: String?): Notification? {
        callLog("CustomNotificationHandler: updateOutgoingCallNotification")
        return buildOngoingCallNotification(callDisplayName ?: "Calling...")
    }

    override fun getSettingUpCallNotification(): Notification? {
        callLog("CustomNotificationHandler: getSettingUpCallNotification")
        return buildOngoingCallNotification("Connecting...")
    }

    private var callStartTime: Long = 0L

    private fun buildOngoingCallNotification(title: String): Notification {
        if (callStartTime == 0L) {
            callStartTime = System.currentTimeMillis()
        }

        // Create intent that opens MainActivity (React Native app)
        val contentIntent = Intent(application, MainActivity::class.java).apply {
            action = Intent.ACTION_MAIN
            addCategory(Intent.CATEGORY_LAUNCHER)
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
        }
        val contentPendingIntent = PendingIntent.getActivity(
            application,
            System.currentTimeMillis().toInt(), // Unique request code to avoid caching
            contentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        return NotificationCompat.Builder(application, ONGOING_CALL_CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_stat_humand)
            .setContentTitle(title)
            .setContentText("Tap to return to call")
            .setOngoing(true)
            .setAutoCancel(false)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setCategory(NotificationCompat.CATEGORY_CALL)
            .setContentIntent(contentPendingIntent)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            // Show elapsed time counter
            .setWhen(callStartTime)
            .setUsesChronometer(true)
            .setChronometerCountDown(false)
            .setShowWhen(true)
            .build()
    }

    /**
     * Reset call start time when a new call begins.
     * Called from StreamVideoManager when initializing a new call.
     */
    fun resetCallStartTime() {
        callStartTime = 0L
    }

    override fun onLiveCall(callId: StreamCallId, callDisplayName: String) {
        callLog("CustomNotificationHandler: onLiveCall ignored for $callId")
    }

    override fun onMissedCall(callId: StreamCallId, callDisplayName: String) {
        callLog("CustomNotificationHandler: onMissedCall ignored for $callId")
    }

    override fun getMissedCallNotification(callId: StreamCallId, callDisplayName: String?): Notification? {
        return null
    }

    override fun onNotification(callId: StreamCallId, callDisplayName: String) {
        callLog("CustomNotificationHandler: onNotification ignored for $callId")
    }
}
