package com.seatel.mobilehall.ui.home.fragment

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.seatel.mobilehall.BuildConfig
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.home.adapter.OrderSummaryAdapter
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.manager.OrderingManager
import com.seatel.mobilehall.databinding.FragmentOrderReviewConfirmBinding
import java.util.*

class OrderReviewConfirmFragment : BaseFragment() {

    // ViewBinding reference
    private var _binding: FragmentOrderReviewConfirmBinding? = null
    private val binding get() = _binding!!

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setFragmentLayout(R.layout.fragment_order_review_confirm)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // Initialize ViewBinding
        _binding = FragmentOrderReviewConfirmBinding.bind(view)

        // Set up clickable term policies
        val clickableSpan = object : ClickableSpan() {
            override fun onClick(textView: View) {
                val uris = Uri.parse("${BuildConfig.BASE_URL}${Constant.urlTerm}")
                val intents = Intent(Intent.ACTION_VIEW, uris)
                val b = Bundle()
                b.putBoolean("new_window", true)
                intents.putExtras(b)
                context?.startActivity(intents)
            }
        }

        val strFirst = SeatelUtils.translatForDialog(
            getmContext(),
            getString(R.string.message_confirm_order_terms_policies)
        )
        val strSecond = SeatelUtils.translatForDialog(
            getmContext(),
            getString(R.string.all_terms_policies)
        )

        val span = SpannableString("$strFirst $strSecond")
        val start = strFirst.length + 1
        val end = start + strSecond.length
        span.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        span.setSpan(
            ForegroundColorSpan(Color.parseColor("#EC008C")),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        binding.ctvTermsPolicies.movementMethod = LinkMovementMethod.getInstance()
        binding.ctvTermsPolicies.setText(span, TextView.BufferType.SPANNABLE)

        // Set up RecyclerView
        binding.rvOrderReviewConfirm.layoutManager = LinearLayoutManager(context)
        binding.rvOrderReviewConfirm.adapter = OrderSummaryAdapter(context)

        // Set total price text
        binding.tvTotal.text =
            String.format(Locale.US, "%.2f", OrderingManager.getInstance().totalSelectedPrice)

        // Handle pickup or delivery visibility and data binding
        if (OrderingManager.getInstance().deliverStatus == OrderingManager.DeliverStatus.PICKUP) {
            binding.layoutPickUp.visibility = View.VISIBLE
            binding.layoutDelivery.visibility = View.GONE
            binding.tvPickDes.text = ""
            binding.tvPickLocation.text = ""
            OrderingManager.getInstance().locationModel?.let {
                binding.tvPickDes.text = it.address
                binding.tvPickLocation.text = it.name
            }
        } else {
            binding.layoutDelivery.visibility = View.VISIBLE
            binding.layoutPickUp.visibility = View.GONE
            binding.tvDeliveryLocation.text = ""
            OrderingManager.getInstance().locationModel?.let {
                binding.tvDeliveryLocation.text = String.format(
                    Locale.US, "%s\n%s", it.address,
                    it.city
                )
            }
        }

        // Set user details
        val nameOrder = OrderingManager.getInstance().firstNameSave + " " + OrderingManager.getInstance().lastNameSave
        binding.tvUsername.text = if (nameOrder.isEmpty()) "N/A" else nameOrder
        SeatelSharePreferences.getInstance(requireContext())?.setUsername(nameOrder)
        binding.tvPhone.text = SeatelUtils.phoneNumberFormat(OrderingManager.getInstance().phoneNumberSave)
        SeatelSharePreferences.getInstance(requireContext())?.setUserPhone(OrderingManager.getInstance().phoneNumberSave)
        binding.tvEmail.text = OrderingManager.getInstance().emailSave
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null  // Clear reference to avoid memory leaks
    }
}
