package com.seyalix.hr.ui.dashboard

import android.os.Bundle
import android.view.*
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.seyalix.hr.R
import com.seyalix.hr.api.ApiClient
import com.seyalix.hr.ui.MainActivity
import com.seyalix.hr.utils.PrefsManager
import kotlinx.coroutines.launch
import kotlinx.coroutines.CancellationException

class DashboardFragment : Fragment() {

    private lateinit var prefs: PrefsManager

    override fun onCreateView(inflater: LayoutInflater, c: ViewGroup?, s: Bundle?): View? =
        inflater.inflate(R.layout.fragment_dashboard, c, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        prefs = PrefsManager(requireContext())

        view.findViewById<TextView>(R.id.tvUserName).text = prefs.getName()
        view.findViewById<TextView>(R.id.tvEmpCode).text  = prefs.getEmpCode()
        view.findViewById<TextView>(R.id.tvRole).text     = prefs.getRole().uppercase()

        // Logout
        view.findViewById<ImageButton>(R.id.btnLogout)?.setOnClickListener {
            (activity as? MainActivity)?.logout()
        }

        loadDashboard(view)
    }

    private fun loadDashboard(view: View) {
        lifecycleScope.launch {
            try {
                val resp = ApiClient.apiService.getDashboard()
                if (resp.isSuccessful && resp.body()?.success == true) {
                    val d = resp.body()!!.data!!
                    activity?.runOnUiThread {
                        // Today badge
                        val tvStatus = view.findViewById<TextView>(R.id.tvTodayStatus)
                        tvStatus.text = d.todayStatus
                        tvStatus.setBackgroundResource(
                            when (d.todayStatus) {
                                "Present"    -> R.drawable.badge_green
                                "Absent"     -> R.drawable.badge_red
                                "Late"       -> R.drawable.badge_orange
                                "Permission" -> R.drawable.badge_blue
                                "Leave"      -> R.drawable.badge_purple
                                else         -> R.drawable.badge_gray
                            }
                        )

                        view.findViewById<TextView>(R.id.tvCheckIn).text  = "In:  ${d.checkIn  ?: "—"}"
                        view.findViewById<TextView>(R.id.tvCheckOut).text = "Out: ${d.checkOut ?: "—"}"

                        val lv = d.leaveBalances.take(4).joinToString("   ") {
                            "${it.code}: ${it.available.toInt()}"
                        }
                        view.findViewById<TextView>(R.id.tvLeaveBalance).text = lv.ifEmpty { "—" }

                        // Pending approvals badge (manager+)
                        // FIX (15 Jul 2026): this badge had no click handler at
                        // all — tapping it did nothing. Now it jumps straight
                        // to the Approvals screen, same as tapping the bell.
                        val tvBadge = view.findViewById<TextView>(R.id.tvPendingBadge)
                        if (prefs.canApprove() && d.pendingApprovalsCount > 0) {
                            tvBadge?.visibility = View.VISIBLE
                            tvBadge?.text = "${d.pendingApprovalsCount} Pending"
                            tvBadge?.setOnClickListener {
                                (activity as? MainActivity)?.openApprovals()
                            }
                        } else {
                            tvBadge?.visibility = View.GONE
                            tvBadge?.setOnClickListener(null)
                        }
                    }
                }
            } catch (e: CancellationException) {
                throw e  // normal when the screen changes mid-request — not a real error
            } catch (e: Exception) {
                activity?.runOnUiThread {
                    Toast.makeText(context, "Dashboard error: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}
