package cpm.com.gskmtorange.dailyentry

import android.content.Context
import android.content.SharedPreferences
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.squareup.okhttp.Callback
import com.squareup.okhttp.HttpUrl
import com.squareup.okhttp.OkHttpClient
import com.squareup.okhttp.Request
import com.squareup.okhttp.Response
import cpm.com.gskmtorange.Database.GSKOrangeDB
import cpm.com.gskmtorange.GetterSetter.CategoryPictureGetterSetter
import cpm.com.gskmtorange.adapter.ScoreAdapter
import cpm.com.gskmtorange.constant.CommonFunctions
import cpm.com.gskmtorange.constant.CommonString
import cpm.com.gskmtorange.databinding.ActivityPdRealtimeReportDetailBinding
import cpm.com.gskmtorange.utils.ScoreItem
import org.json.JSONObject
import android.os.Handler
import android.os.Looper
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import java.text.SimpleDateFormat
import java.util.Locale

class PD_Realtime_Report_Detail : AppCompatActivity() {
    private var context: Context? = null
    var categoryName: String? = null
    var categoryId: String? = null
    var store_id: String? = null;
    var date: String? = null;
    var lang: String? = null;
    var store_type_id: String? = null
    var class_id: String? = null
    var key_account_id: String? = null
    var country_id: String? = null
    var pd_categoryId: String? = null
    var subcat_name: String? = null
    var store_flag_str: String? = null
    private var preferences: SharedPreferences? = null
    var db: GSKOrangeDB? = null
    var listdat: ArrayList<CategoryPictureGetterSetter>? = ArrayList()
    var username: String? = ""
    private var kpi_name: String? = ""
    private lateinit var binding: ActivityPdRealtimeReportDetailBinding
    val PERMISSION_ALL: Int = 99
    private var _pos = -1;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPdRealtimeReportDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(binding.toolbar)
        context = this
        preferences = PreferenceManager.getDefaultSharedPreferences(context)
        preferences?.let {
            lang = it.getString(CommonString.KEY_LANGUAGE, "")
            store_id = it.getString(CommonString.KEY_STORE_ID, "")
            username = it.getString(CommonString.KEY_USERNAME, "")
            store_type_id = it.getString(CommonString.KEY_STORETYPE_ID, "")
            class_id = it.getString(CommonString.KEY_CLASS_ID, "")
            key_account_id = it.getString(CommonString.KEY_KEYACCOUNT_ID, "")
            country_id = it.getString(CommonString.KEY_COUNTRY_ID, "")
            store_flag_str = it.getString(CommonString.KEY_STORE_FLAG, "")
            date = it.getString(CommonString.KEY_DATE, "")
        }
        CommonFunctions.updateLangResources(
            context, preferences?.getString(CommonString.KEY_LANGUAGE, "")
        )
        intent?.let {
            categoryName = it.getStringExtra("categoryName")
            categoryId = it.getStringExtra("categoryId")
            kpi_name = it.getStringExtra("kpi_name")
            pd_categoryId = it.getStringExtra("pd_subcat_code")
            subcat_name = it.getStringExtra("subcat_name")
            Log.d("pdcode",pd_categoryId.toString())
        }
        supportActionBar?.apply {
            setHomeButtonEnabled(true)
            setDisplayHomeAsUpEnabled(true)
            title = kpi_name
        }
        preferences?.getString(CommonString.KEY_PD_PROJECT_Id, "")?.let { projectId ->
            val userId = preferences?.getString(CommonString.KEY_PD_USER_Id, "")
                .takeIf { !it.isNullOrBlank() } ?: username
            Log.d("pd_user_id", userId.toString());

        }
        if (isNetworkAvailable(this@PD_Realtime_Report_Detail)) {
            fetchlivedata()
        } else {
            Toast.makeText(this, "No internet connection", Toast.LENGTH_SHORT).show()
        }
    }


    private fun fetchlivedata() {
        Log.d("apidata",date +","+store_id+","+pd_categoryId+","+preferences?.getString(CommonString.KEY_PD_PROJECT_Id, ""))

        Handler(Looper.getMainLooper()).post {
            binding.progressBar.visibility = View.VISIBLE
            binding.recyclerView.visibility = View.GONE
        }

        val client = OkHttpClient()
        val formattedDate = formatDate(date)
        val urlBuilder = HttpUrl.Builder()
            .scheme("https")
            .host("apis.shelfwatch.io")
            .addPathSegment("get_haleon_insights")
            .addQueryParameter("visit_date", formattedDate)
            .addQueryParameter("store_id", store_id)
            .addQueryParameter("category_id", pd_categoryId)
            .addQueryParameter("project_id", preferences?.getString(CommonString.KEY_PD_PROJECT_Id, ""))

        val request = Request.Builder()
            .url(urlBuilder.build())
            .build()
        Log.d("apiparams",request.toString() + ","+urlBuilder)

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(request: Request?, e: java.io.IOException?) {
                Log.e("RealtimeReport", "API call failed", e)
                Handler(Looper.getMainLooper()).post {
                    binding.progressBar.visibility = View.GONE
                    binding.recyclerView.visibility = View.VISIBLE
                }
            }

            override fun onResponse(response: Response?) {
                Handler(Looper.getMainLooper()).post {
                    binding.progressBar.visibility = View.GONE
                    binding.recyclerView.visibility = View.VISIBLE
                }
                val responseData = response?.body()?.string()
                Log.d("responsedata", responseData.toString())

                responseData?.let { jsonStr ->
                    try {
                        val json = JSONObject(jsonStr)
                        val output = json.getJSONObject("output")
                        val report = output.getJSONObject("report")
                        val overallArray = report.getJSONArray("overall")
                        val imagelist = output.getJSONArray("images")

                        var osa = "0%"
                        var msl = "0%"
                        var posm = "0%"
                        var sosSku = "0%"
                        var sosBrand = "0%"

                        for (i in 0 until overallArray.length()) {
                            val obj = overallArray.getJSONObject(i)
                            when (obj.getString("kpi_name")) {
                                "OSA" -> osa = obj.getString("value")
                                "MSL OSA" -> msl = obj.getString("value")
                                "POSM" -> posm = obj.getString("value")
                                "SOS - SKU Level" -> sosSku = obj.getString("value")
                                "SOS - Brand Level" -> sosBrand = obj.getString("value")
                            }
                        }

                        // Build OverallScore
                        val scoreItems = mutableListOf<ScoreItem>()
                        scoreItems.add(
                            ScoreItem.OverallScore(
                                osa = osa,
                                msl = msl,
                                posm = posm,
                                sosSku = sosSku,
                                sosBrand = sosBrand
                            )
                        )

                        // ===== Brand Details for "Toothpaste" =====
                        val detailedArray = report.getJSONArray("detailed")
                        var brandDetails: List<Pair<String, String>> = emptyList()

                        for (i in 0 until detailedArray.length()) {
                            val detail = detailedArray.getJSONObject(i)
                            if (detail.getString("kpi_name") == "SOS - Brand Level") {
                                val dataArray = detail.getJSONArray("data")
                                val brands = mutableListOf<Pair<String, String>>()
                                for (j in 0 until dataArray.length()) {
                                    val brandObj = dataArray.getJSONObject(j)
                                    val brandName = brandObj.optString("brand_name", "Unknown")
                                    val value = brandObj.getString("value")
                                    if (brandName.isNotEmpty() && brandName != "null") {
                                        brands.add(brandName to value)
                                    }
                                }
                                brandDetails = brands
                            }
                        }

                        scoreItems.add(
                            ScoreItem.CategoryScore(
                                categoryName = subcat_name.toString(),
                                msl = msl,
                                posm = posm,
                                sosSku = sosSku,
                                sosBrand = sosBrand,
                                brandDetails = brandDetails
                            )
                        )

                        // ===== IMAGE ITEMS =====
                        if (imagelist.length()>0) {
                            for (i in 0 until imagelist.length()) {
                                val imgObj = imagelist.getJSONObject(i)
                                val rawImages = imgObj.getJSONArray("raw_images")
                                for (j in 0 until rawImages.length()) {
                                    val imgObjnew = rawImages.getJSONObject(j)
                                    val url = imgObjnew.getString("url")
                                    Log.d("imgurl",url);
                                    scoreItems.add(ScoreItem.ImageItem(url))
                                }
                            }
                        }

                        // Update UI on main thread
                        Handler(Looper.getMainLooper()).post {
                            binding.recyclerView.layoutManager = LinearLayoutManager(context)
                            binding.recyclerView.adapter = ScoreAdapter(scoreItems)
                        }

                    } catch (e: Exception) {
                        Log.e("RealtimeReport", "Parse error", e)
                    }
                }
            }
        })
    }

    private fun formatDate(inputDate: String?): String {
        return try {
            // Parse input date (from "MM/dd/yyyy")
            val inputFormat = SimpleDateFormat("MM/dd/yyyy", Locale.US)
            val date = inputFormat.parse(inputDate ?: "")

            // Format to "yyyy-MM-dd" for API, using Locale.US to avoid locale-specific digits
            val outputFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
            if (date != null) outputFormat.format(date) else ""
        } catch (e: Exception) {
            ""
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                // Finish the current activity and go back
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        val network = connectivityManager.activeNetwork ?: return false
        val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false

        return when {
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
            else -> false
        }
    }

}