package com.jiooption.trading

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.*
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import com.jiooption.trading.ui.auth.LoginActivity
import com.jiooption.trading.ui.deposit.DepositActivity
import com.jiooption.trading.utils.Constants
import com.jiooption.trading.webview.JsBridge
import com.jiooption.trading.webview.WebViewManager
import com.google.android.material.bottomnavigation.BottomNavigationView

/**
 * Main activity with bottom navigation and WebView
 * Each tab loads a different web page from the PHP backend
 */
class MainActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MainActivity"
    }

    private lateinit var webView: WebView
    private lateinit var bottomNav: BottomNavigationView
    private lateinit var progressBar: ProgressBar

    private var currentUrl = ""

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        webView = findViewById(R.id.webView)
        bottomNav = findViewById(R.id.bottomNav)
        progressBar = findViewById(R.id.progressBar)

        // Setup WebView
        WebViewManager.setupWebView(webView, this)
        webView.addJavascriptInterface(JsBridge(this), JsBridge.BRIDGE_NAME)

        // WebView client
        webView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                progressBar.visibility = View.VISIBLE
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                progressBar.visibility = View.GONE
                // Save cookies after page loads
                url?.let { WebViewManager.saveCookiesFromWebView(it) }
            }

            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                val url = request?.url?.toString() ?: return false

                // Handle external URLs
                if (!url.startsWith(Constants.BASE_URL)) {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    startActivity(intent)
                    return true
                }

                // Handle internal navigation - update bottom nav if needed
                updateBottomNavForUrl(url)
                return false
            }

            override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                if (request?.isForMainFrame == true) {
                    progressBar.visibility = View.GONE
                    Log.e(TAG, "WebView error: ${error?.description}")
                }
            }
        }

        // WebChrome client for progress
        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                if (newProgress >= 100) {
                    progressBar.visibility = View.GONE
                }
            }
        }

        // Bottom navigation
        bottomNav.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.nav_dashboard -> loadUrl(Constants.dashboardUrl())
                R.id.nav_trade -> loadUrl(Constants.tradeUrl())
                R.id.nav_deposit -> {
                    // Open native deposit activity
                    startActivity(Intent(this, DepositActivity::class.java))
                    return@setOnItemSelectedListener false
                }
                R.id.nav_withdraw -> loadUrl(Constants.withdrawUrl())
                R.id.nav_profile -> loadUrl(Constants.profileUrl())
            }
            true
        }

        // Load initial page (Dashboard)
        loadUrl(Constants.dashboardUrl())
    }

    private fun loadUrl(url: String) {
        if (url != currentUrl) {
            currentUrl = url
            WebViewManager.syncCookies(this)
            webView.loadUrl(url)
        }
    }

    private fun updateBottomNavForUrl(url: String) {
        val navId = when {
            url.contains("dashboard") -> R.id.nav_dashboard
            url.contains("trade") -> R.id.nav_trade
            url.contains("deposit") -> R.id.nav_deposit
            url.contains("withdraw") -> R.id.nav_withdraw
            url.contains("profile") || url.contains("referral") ||
            url.contains("support") || url.contains("kyc") -> R.id.nav_profile
            else -> null
        }
        if (navId != null) {
            bottomNav.menu.findItem(navId)?.isChecked = true
        }
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onResume() {
        super.onResume()
        WebViewManager.syncCookies(this)
        // Refresh current page to get updated balance
        webView.reload()
    }

    override fun onDestroy() {
        webView.removeJavascriptInterface(JsBridge.BRIDGE_NAME)
        webView.destroy()
        super.onDestroy()
    }
}
