package com.seyalix.hr.ui

import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.seyalix.hr.BuildConfig
import com.seyalix.hr.R
import com.seyalix.hr.api.ApiClient
import com.seyalix.hr.ui.approvals.ApprovalsFragment
import com.seyalix.hr.ui.attendance.AttendanceFragment
import com.seyalix.hr.ui.auth.LoginActivity
import com.seyalix.hr.ui.dashboard.DashboardFragment
import com.seyalix.hr.ui.leave.LeaveFragment
import com.seyalix.hr.ui.muster.MusterFragment
import com.seyalix.hr.ui.notifications.NotificationsFragment
import com.seyalix.hr.ui.reports.ReportsFragment
import com.seyalix.hr.utils.PrefsManager
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private lateinit var prefs: PrefsManager

    // ── Pending-approval polling ────────────────────────────────
    // This is the piece that actually makes leave/permission/late/muster
    // requests "reach" the reporting head: previously the Approvals screen
    // only checked the server when a manager happened to open it manually
    // (and, until the matching endpoints were added server-side, the
    // permission/late tabs silently showed nothing even then). Now the app
    // polls in the background while open and raises a notification + badge
    // the moment something new is pending. No server push (FCM) needed.
    private val pollHandler = Handler(Looper.getMainLooper())
    private val pollIntervalMs = 30_000L
    private var polling = false
    private var lastKnownTotal = 0

    private val pollRunnable = object : Runnable {
        override fun run() {
            checkPendingApprovals()
            pollHandler.postDelayed(this, pollIntervalMs)
        }
    }

    // ── Personal notifications polling (FIX 10 Jul 2026) ────────
    // Same pattern as the approvals poller above, but for the personal
    // notifications bell (apply/approve/reject alerts etc) — runs for
    // EVERY role, not just approvers, since everyone gets these.
    private val notifPollHandler = Handler(Looper.getMainLooper())
    private var notifPolling = false
    private var lastKnownUnreadNotifs = 0

    private val notifPollRunnable = object : Runnable {
        override fun run() {
            checkNotifications()
            notifPollHandler.postDelayed(this, pollIntervalMs)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        prefs = PrefsManager(this)
        createNotificationChannel()
        createNotifChannel()
        requestNotificationPermissionIfNeeded()

        if (savedInstanceState == null) {
            if (intent.getBooleanExtra("open_notifications", false)) {
                loadFragment(NotificationsFragment())
            } else {
                loadFragment(DashboardFragment())
            }
        }

        findViewById<com.google.android.material.bottomnavigation.BottomNavigationView>(R.id.bottomNav)
            .setOnItemSelectedListener { item ->
                when (item.itemId) {
                    R.id.nav_dashboard -> { loadFragment(DashboardFragment()); true }
                    R.id.nav_attendance -> { loadFragment(AttendanceFragment()); true }
                    R.id.nav_leave -> { loadFragment(LeaveFragment()); true }
                    R.id.nav_muster -> { loadFragment(MusterFragment()); true }
                    R.id.nav_more -> { showMoreMenu(); false } // don't visually select "More"
                    else -> { loadFragment(DashboardFragment()); true }
                }
            }

        // Update-available popup — same idea as a phone's system update
        // popup: check once per app launch, and if the vendor has pushed
        // a newer build, show it with an "Update Now" button. Doesn't
        // block the rest of the app (this app has no forced-update
        // column yet), so it's safe even if the check fails or is slow.
        checkAppUpdate()
    }

    override fun onResume() {
        super.onResume()
        // Only reporting heads (manager/hr/admin/superadmin) ever have
        // anything to approve, so don't waste calls polling for employees.
        if (prefs.canApprove() && !polling) {
            polling = true
            pollHandler.post(pollRunnable)
        }
        // Personal notifications apply to every role.
        if (!notifPolling) {
            notifPolling = true
            notifPollHandler.post(notifPollRunnable)
        }
    }

    override fun onPause() {
        super.onPause()
        pollHandler.removeCallbacks(pollRunnable)
        polling = false
        notifPollHandler.removeCallbacks(notifPollRunnable)
        notifPolling = false
    }

    private fun checkPendingApprovals() {
        lifecycleScope.launch {
            try {
                val resp = ApiClient.apiService.getPendingCounts()
                if (resp.isSuccessful && resp.body()?.success == true) {
                    val total = resp.body()?.data?.total ?: 0
                    lastKnownTotal = total
                    updateApprovalBadge(total)

                    val lastSeen = prefs.getLastSeenApprovalCount()
                    if (total > lastSeen) {
                        showApprovalNotification(total - lastSeen, total)
                        prefs.setLastSeenApprovalCount(total)
                    } else if (total < lastSeen) {
                        // some got approved/rejected elsewhere (web or another
                        // device) — bring the "seen" baseline back down too
                        prefs.setLastSeenApprovalCount(total)
                    }
                }
            } catch (_: Exception) {
                // Background poll — fail silently and try again next tick.
            }
        }
    }

    private fun checkNotifications() {
        lifecycleScope.launch {
            try {
                val resp = ApiClient.apiService.getUnreadNotificationCount()
                if (resp.isSuccessful && resp.body()?.success == true) {
                    val count = resp.body()?.data?.count ?: 0
                    lastKnownUnreadNotifs = count

                    val lastSeen = prefs.getLastSeenNotifCount()
                    if (count > lastSeen) {
                        showNotificationPopup(count - lastSeen, count)
                        prefs.setLastSeenNotifCount(count)
                    } else if (count < lastSeen) {
                        // some got read elsewhere (web or another device) —
                        // bring the "seen" baseline back down too
                        prefs.setLastSeenNotifCount(count)
                    }
                }
            } catch (_: Exception) {
                // Background poll — fail silently and try again next tick.
            }
        }
    }

    private fun updateApprovalBadge(total: Int) {
        val nav = findViewById<com.google.android.material.bottomnavigation.BottomNavigationView>(R.id.bottomNav)
        if (total > 0) {
            val badge = nav.getOrCreateBadge(R.id.nav_more)
            badge.isVisible = true
            badge.number = total
        } else {
            nav.removeBadge(R.id.nav_more)
        }
    }

    private fun showApprovalNotification(newCount: Int, total: Int) {
        if (Build.VERSION.SDK_INT >= 33 &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
            != PackageManager.PERMISSION_GRANTED
        ) {
            return // no permission — the badge dot on "More" still shows it
        }
        val intent = Intent(this, MainActivity::class.java)
        val pending = PendingIntent.getActivity(
            this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        val text = if (newCount == 1) "1 new request needs your approval"
                   else "$newCount new requests need your approval"
        val notif = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle("Pending approvals ($total)")
            .setContentText(text)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            .setContentIntent(pending)
            .build()
        (getSystemService(NOTIFICATION_SERVICE) as NotificationManager)
            .notify(APPROVAL_NOTIF_ID, notif)
    }

    // FIX (10 Jul 2026): popup for personal notifications — same mechanism
    // as showApprovalNotification above, separate channel/id so the two
    // don't stomp on each other, and tapping it opens NotificationsFragment
    // directly instead of just the dashboard.
    private fun showNotificationPopup(newCount: Int, total: Int) {
        if (Build.VERSION.SDK_INT >= 33 &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
            != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }
        val intent = Intent(this, MainActivity::class.java).apply {
            putExtra("open_notifications", true)
        }
        val pending = PendingIntent.getActivity(
            this, 1, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        val text = if (newCount == 1) "You have 1 new notification"
                   else "You have $newCount new notifications"
        val notif = NotificationCompat.Builder(this, NOTIF_CHANNEL_ID)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle("Notifications ($total unread)")
            .setContentText(text)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true)
            .setContentIntent(pending)
            .build()
        (getSystemService(NOTIFICATION_SERVICE) as NotificationManager)
            .notify(NOTIF_ID, notif)
    }

    private fun requestNotificationPermissionIfNeeded() {
        if (Build.VERSION.SDK_INT >= 33 &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
            != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1001)
        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID, "Pending Approvals", NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "Leave, permission, late & muster requests waiting for your approval"
            }
            (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
        }
    }

    // FIX (10 Jul 2026): separate channel for personal notifications, so
    // users can mute/configure it independently from approval alerts.
    private fun createNotifChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                NOTIF_CHANNEL_ID, "Notifications", NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "Alerts about your own leave, permission, and late-mark requests"
            }
            (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
        }
    }

    // ── App Update popup ─────────────────────────────────────────
    // Calls the public ?action=app_version endpoint (no login needed),
    // compares it against this build's versionCode, and — if the
    // vendor has pushed something newer — shows a popup with an
    // "Update Now" button that opens the APK/Play Store URL, just like
    // a phone's own "system update available" popup. "Later" just
    // dismisses it; it'll ask again next launch until they update.
    private fun checkAppUpdate() {
        lifecycleScope.launch {
            try {
                val resp = ApiClient.apiService.getAppVersion()
                if (!resp.isSuccessful) return@launch
                val info = resp.body()?.data ?: return@launch
                if (info.latestVersionCode <= BuildConfig.VERSION_CODE) return@launch // already latest

                if (isFinishing || isDestroyed) return@launch
                AlertDialog.Builder(this@MainActivity)
                    .setTitle("Update Available — v${info.latestVersionName}")
                    .setMessage(info.message)
                    .setCancelable(true)
                    .setPositiveButton("Update Now") { _, _ ->
                        if (info.updateUrl.isNotBlank()) {
                            try {
                                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(info.updateUrl)))
                            } catch (e: Exception) {
                                // Bad/unreachable update_url configured server-side — fail
                                // quietly, don't crash the app over a broken link.
                            }
                        }
                    }
                    .setNegativeButton("Later", null)
                    .show()
            } catch (e: Exception) {
                // Network hiccup / server not reachable — don't bother the
                // user, just skip the popup for this launch and try again
                // next time.
            }
        }
    }

    // BottomNavigationView supports a max of 5 items, so less-frequently-used
    // sections (Approvals, Reports) live behind this "More" picker instead.
    private fun showMoreMenu() {
        val options = arrayOf("Notifications", "Approvals", "Reports", "Logout")
        AlertDialog.Builder(this)
            .setTitle("More")
            .setItems(options) { _, which ->
                when (which) {
                    0 -> openNotifications()
                    1 -> openApprovals()
                    2 -> loadFragment(ReportsFragment())
                    3 -> logout()
                }
            }
            .show()
    }

    private fun loadFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragmentContainer, fragment)
            .commit()
    }

    // Called from DashboardFragment's logout button, or the "More" menu
    fun logout() {
        PrefsManager(this).logout()
        val intent = Intent(this, LoginActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
        finish()
    }

    // FIX (15 Jul 2026): the "X Pending" badge on the dashboard had no
    // click handler at all — tapping it did nothing. DashboardFragment
    // calls this to jump straight to the Approvals screen.
    fun openApprovals() {
        prefs.setLastSeenApprovalCount(lastKnownTotal)
        updateApprovalBadge(0)
        loadFragment(ApprovalsFragment())
    }

    fun openNotifications() {
        prefs.setLastSeenNotifCount(lastKnownUnreadNotifs)
        loadFragment(NotificationsFragment())
    }

    companion object {
        private const val CHANNEL_ID = "pending_approvals"
        private const val APPROVAL_NOTIF_ID = 4201
        private const val NOTIF_CHANNEL_ID = "personal_notifications"
        private const val NOTIF_ID = 4202
    }
}
