package cpm.com.gskmtorange.dailyentry

import android.annotation.SuppressLint
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.preference.PreferenceManager
import android.provider.MediaStore
import android.util.Base64
import android.util.Log
import android.view.View
import android.webkit.ConsoleMessage
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import cpm.com.gskmtorange.Database.GSKOrangeDB
import cpm.com.gskmtorange.constant.CommonString
import cpm.com.gskmtorange.databinding.ActivityWebviewBinding
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class WebViewActivity : AppCompatActivity() {
    private lateinit var binding: ActivityWebviewBinding
    var toolbar: Toolbar? = null
    private lateinit var type : String
    private var player: ExoPlayer? = null
   // private var player : ExoPlayer? = null
   private var pageStartTime: Long = 0
   private var pageEndTime: Long = 0
   private lateinit var preferences: SharedPreferences
   private lateinit var db: GSKOrangeDB
   private var storeid: String = ""
   private var detailerId: String = ""
   private var categoryId: String = ""
    private var dt_level: String = ""

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWebviewBinding.inflate(layoutInflater)
        setContentView(binding.root)

        preferences = PreferenceManager.getDefaultSharedPreferences(this)
        db = GSKOrangeDB(this)
        db.open()

        val url = intent.getStringExtra("url") ?: ""
        type = intent.getStringExtra("type") ?: "html-webview"
        storeid = intent.getStringExtra("storeid") ?: ""
        detailerId = intent.getStringExtra("merid") ?: ""
        categoryId = intent.getStringExtra("categoryId") ?: ""
        dt_level = intent.getStringExtra("dt_level") ?: ""
        handleContent(type, url)

        binding.toolbar.setTitle("Banner Detail")
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        if(dt_level.isNotEmpty()){
            pageStartTime = System.currentTimeMillis()
            val formattedTime = SimpleDateFormat(
                "HH:mm:ss",
                Locale.getDefault()
            ).format(Date(pageStartTime))
            Log.d("WEBVIEW_START_TIME", "Start time is :$formattedTime ")
        }

    }

    private fun handleContent(type: String, url: String) {
        when (type) {
            "html-webview" -> {
                binding.webView.visibility = View.VISIBLE
                binding.imageView.visibility = View.GONE
                binding.videoView.visibility = View.GONE
                setupWebView(url)
            }

            "image" -> {
                binding.webView.visibility = View.GONE
                binding.imageView.visibility = View.VISIBLE
                binding.videoView.visibility = View.GONE

                com.bumptech.glide.Glide.with(this)
                    .load(url)
                    .into(binding.imageView)
            }

            "video" -> {
                binding.webView.visibility = View.GONE
                binding.imageView.visibility = View.GONE
                binding.videoView.visibility = View.VISIBLE
                playVideo(url)
            }

            "html-webbrowser" -> {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                finish()
            }

            else -> {
                binding.webView.visibility = View.VISIBLE
                setupWebView(url)
            }
        }
    }

    private fun playVideo(url: String) {
        player = ExoPlayer.Builder(this).build()
        binding.videoView.post {
            val width = binding.videoView.width
            val height = (width * 9) / 16
            binding.videoView.layoutParams.height = height
        }

        binding.videoView.player = player

        val mediaItem = MediaItem.fromUri(url)
        player?.setMediaItem(mediaItem)
        player?.prepare()
        player?.play()
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun setupWebView(url: String) {
        with(binding.webView.settings) {
            javaScriptEnabled = true
            domStorageEnabled = true
            javaScriptCanOpenWindowsAutomatically = true
            setSupportMultipleWindows(true)
            loadWithOverviewMode = true

            setSupportZoom(true)
            builtInZoomControls = true
            displayZoomControls = false
            useWideViewPort = true
            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW


        }

        binding.webView.addJavascriptInterface(WebAppInterface(), "Android")

        binding.webView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
               /* pageStartTime = System.currentTimeMillis()
                val formattedTime = SimpleDateFormat(
                    "HH:mm:ss",
                    Locale.getDefault()
                ).format(Date(pageStartTime))*/

                // println(formattedTime)
                injectJS(view)
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                pageStartTime = System.currentTimeMillis()
                Log.d("WEBVIEW_TIME", " viewed for $pageStartTime sec")
                injectJS(view)
            }
        }

        binding.webView.webChromeClient = object : WebChromeClient() {
            override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
                Log.e("JS_LOG", consoleMessage?.message() ?: "")
                return true
            }
        }
        binding.webView.loadUrl(url)
    }

    // 🔥 JS INJECTION (RN BRIDGE + FIXES)
    private fun injectJS(view: WebView?) {

        view?.evaluateJavascript(
            """
            (function() {

                console.log("🔥 JS INJECTED");
                
                 var meta = document.querySelector('meta[name=viewport]');
    if (meta) {
        meta.setAttribute(
            'content',
            'width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes'
        );
    } else {
        var newMeta = document.createElement('meta');
        newMeta.name = "viewport";
        newMeta.content = "width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes";
        document.head.appendChild(newMeta);
    }

                // ✅ imageToBase64 FIX
                window.imageToBase64 = function(img) {
                    try {
                        if (!img) return null;

                        var canvas = document.createElement('canvas');
                        canvas.width = img.naturalWidth || img.width;
                        canvas.height = img.naturalHeight || img.height;

                        var ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0);

                        return canvas.toDataURL('image/png');

                    } catch(e) {
                        console.log("imageToBase64 error:", e);
                        return null;
                    }
                };

                // ✅ React Native bridge
                window.ReactNativeWebView = {
                    postMessage: function(data) {
                        console.log("POST MESSAGE:", data);
                        Android.postMessage(data);
                    }
                };

                // ✅ Share function
                window.nativeShare = function(options) {
                    console.log("CALL nativeShare:", options);

                    if (!options) return;

                    window.ReactNativeWebView.postMessage(JSON.stringify({
                        type: 'SHARE',
                        data: options
                    }));
                };

                // 🔍 Debug click
                document.addEventListener('click', function(e) {
                    console.log("CLICK:", e.target.innerText);
                }, true);

            })();
            """.trimIndent(),
            null
        )
    }

    // ✅ JS INTERFACE
    inner class WebAppInterface {

        @JavascriptInterface
        fun postMessage(message: String?) {
            Log.e("WEB_MESSAGE", "RAW: $message")

            runOnUiThread {
                handleWebMessage(message)
            }
        }
    }

    // ✅ HANDLE MESSAGE
    private fun handleWebMessage(message: String?) {
        try {
            val obj = JSONObject(message ?: return)
            val type = obj.optString("type")

            if (type == "SHARE") {
                val data = obj.optJSONObject("data")
                handleShare(data)
            }

        } catch (e: Exception) {
            Log.e("WEB_MESSAGE", "Error: ${e.message}")
        }
    }

    // ✅ HANDLE SHARE
    private fun handleShare(data: JSONObject?) {

        if (data == null) return

        val type = data.optString("type")
        val message = data.optString("message")
        val url = data.optString("url")
        val image = data.optString("image")
        val imagesArray = data.optJSONArray("images")

        Log.e("SHARE_DEBUG", "TYPE: $type")
        Log.e("SHARE_DEBUG", "MESSAGE: $message")
        Log.e("SHARE_DEBUG", "URL: $url")
        Log.e("SHARE_DEBUG", "IMAGE: ${image.take(50)}")

        when (type) {

            "text" -> shareText("$message\n$url")

            "image" -> {
                if (image.isNotEmpty()) shareImageSmart(image)
            }

            "multiple_images" -> {
                if (imagesArray != null) {
                    val list = mutableListOf<String>()
                    for (i in 0 until imagesArray.length()) {
                        list.add(imagesArray.getString(i))
                    }
                    shareMultipleImages(list)
                }
            }

            "image_with_text" -> {
                if (image.isNotEmpty()) {
                    shareImageTextSmart(image, "$message\n$url")
                }
            }
            else -> shareText(message)
        }
    }

    // ✅ TEXT SHARE
    private fun shareText(text: String) {
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "text/plain"
        intent.putExtra(Intent.EXTRA_TEXT, text)
        startActivity(Intent.createChooser(intent, "Share via"))
    }

    // ✅ SMART IMAGE SHARE (BASE64 + URL)
    private fun shareImageSmart(imageData: String) {

        Log.e("SHARE_DEBUG", "Image Data: ${imageData.take(100)}")

        try {
            if (imageData.startsWith("data:image")) {

                val pure = imageData.substringAfter(",")
                val bytes = Base64.decode(pure, Base64.DEFAULT)
                val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)

                val path = MediaStore.Images.Media.insertImage(contentResolver, bitmap, "Image", null)
                val uri = Uri.parse(path)

                val intent = Intent(Intent.ACTION_SEND)
                intent.type = "image/*"
                intent.putExtra(Intent.EXTRA_STREAM, uri)

                startActivity(Intent.createChooser(intent, "Share Image"))

            } else {
                // URL → Glide
                com.bumptech.glide.Glide.with(this)
                    .asBitmap()
                    .load(imageData)
                    .into(object : com.bumptech.glide.request.target.CustomTarget<android.graphics.Bitmap>() {

                        override fun onResourceReady(
                            resource: android.graphics.Bitmap,
                            transition: com.bumptech.glide.request.transition.Transition<in android.graphics.Bitmap>?
                        ) {

                            val path = MediaStore.Images.Media.insertImage(
                                contentResolver, resource, "Image", null
                            )

                            val uri = Uri.parse(path)

                            val intent = Intent(Intent.ACTION_SEND)
                            intent.type = "image/*"
                            intent.putExtra(Intent.EXTRA_STREAM, uri)

                            startActivity(Intent.createChooser(intent, "Share Image"))
                        }

                        override fun onLoadCleared(placeholder: android.graphics.drawable.Drawable?) {}
                    })
            }

        } catch (e: Exception) {
            Log.e("SHARE_DEBUG", "Error: ${e.message}")
        }
    }

    // ✅ IMAGE + TEXT
    private fun shareImageTextSmart(imageData: String, text: String) {

        if (imageData.startsWith("data:image")) {

            val pure = imageData.substringAfter(",")
            val bytes = Base64.decode(pure, Base64.DEFAULT)
            val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)

            val path = MediaStore.Images.Media.insertImage(contentResolver, bitmap, "Image", null)
            val uri = Uri.parse(path)
            val intent = Intent(Intent.ACTION_SEND)
            intent.type = "image/*"
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.putExtra(Intent.EXTRA_TEXT, text)
            startActivity(Intent.createChooser(intent, "Share"))
        } else {
            shareText(text)
        }
    }

    // ✅ MULTIPLE IMAGES
    private fun shareMultipleImages(list: List<String>) {
        val uris = ArrayList<Uri>()
        for (base64 in list) {
            val pure = base64.substringAfter(",")
            val bytes = Base64.decode(pure, Base64.DEFAULT)
            val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)

            val path = MediaStore.Images.Media.insertImage(contentResolver, bitmap, "Image", null)
            uris.add(Uri.parse(path))
        }
        val intent = Intent(Intent.ACTION_SEND_MULTIPLE)
        intent.type = "image/*"
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
        startActivity(Intent.createChooser(intent, "Share Images"))
    }
    override fun onSupportNavigateUp(): Boolean {
        onBackPressedDispatcher.onBackPressed()
        return true
    }

    override fun onBackPressed() {
        if (binding.webView.canGoBack()) {
            binding.webView.goBack()
        } else {
            super.onBackPressed()
        }
    }
    override fun onPause() {
        super.onPause()
        player?.pause()
        val visit_date = preferences.getString(CommonString.KEY_DATE, "") ?: ""
        val user_id = preferences.getString(CommonString.KEY_USERNAME, "") ?: ""
        if(dt_level.isNotEmpty()) {
            pageEndTime = System.currentTimeMillis()
            val start_time =
                SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date(pageStartTime))
            val end_time =
                SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date(pageEndTime))
            val spent = (pageEndTime - pageStartTime) / 1000
            db.insertWebViewTimeSpent(
                storeid,
                visit_date,
                start_time,
                end_time,
                spent.toString(),
                detailerId,
                user_id,
                categoryId,
                dt_level
            )
           // Log.d("WEBVIEW_END_TIME", "End time is :$end_time and viewed for $spent sec ")
           /* var detailer_xml = ""
            var  onXML = ""
            val detailerList = db.getUploadedDetailerData(storeid)
            Log.d("detailersize", detailerList.size.toString());
            if (!detailerList.isEmpty()) {
                for (j in detailerList.indices) {
                    onXML =
                        "[DETAILER_DATA]" +
                                "[MID]" + 0 + "[/MID]" +
                                "[USERID]" + user_id + "[/USERID]" +
                                "[STORE_ID]" + storeid + "[/STORE_ID]" +
                                "[VISIT_DATE]" + detailerList.get(j)!!
                            .getVisitdate() + "[/VISIT_DATE]" +
                                "[START_TIME]" + detailerList.get(j)!!
                            .getStart_time() + "[/START_TIME]" +
                                "[END_TIME]" + detailerList.get(j)!!.getEnd_time() + "[/END_TIME]" +
                                "[DURATION]" + detailerList.get(j)!!.getDuration() + "[/DURATION]" +
                                "[DETAILER_ID]" + detailerList.get(j)!!
                            .getDetailerId() + "[/DETAILER_ID]" +
                                "[CATEGORY_ID]" + detailerList.get(j)!!
                            .getCATEGORY_ID().get(0) + "[/CATEGORY_ID]" +
                                "[DT_LEVEL]" + detailerList.get(j)!!.getDT_LEVEL().get(0) + "[/DT_LEVEL]" +
                                "[/DETAILER_DATA]"

                    detailer_xml = detailer_xml + onXML
                }
                val sos_xml = "[DATA]" + detailer_xml + "[/DATA]"
                Log.e("detailer_xml_data", sos_xml)

                Log.d("WEBVIEW_END_TIME", "End time is :$end_time and viewed for $spent sec ")
            }*/
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        player?.release()
        player = null
    }
}