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
                                "Present (On Duty)" -> R.drawable.badge_green
                                "Absent"            -> R.drawable.badge_red
                                "Half Day"          -> R.drawable.badge_orange
                                "On Leave"          -> R.drawable.badge_purple
                                "Late"              -> R.drawable.badge_orange
                                "Permission"        -> R.drawable.badge_blue
                                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 leaves stat card
                        view.findViewById<TextView>(R.id.tvPendingLeavesCount).text = d.pendingLeaves.toString()
                        view.findViewById<View>(R.id.cardPendingLeaves)?.setOnClickListener {
                            (activity as? MainActivity)?.let {
                                it.supportFragmentManager.beginTransaction()
                                    .replace(R.id.fragmentContainer, com.seyalix.hr.ui.leave.LeaveFragment())
                                    .commit()
                            }
                        }

                        // Active notices stat card
                        view.findViewById<TextView>(R.id.tvNoticesCount).text = d.notices.size.toString()

                        // Latest payslip stat card
                        val payslip = d.latestPayslip
                        if (payslip != null) {
                            view.findViewById<TextView>(R.id.tvPayslipMonth).text =
                                "${monthName(payslip.month)} ${payslip.year}"
                            view.findViewById<TextView>(R.id.tvPayslipAmount).text =
                                "₹${"%,.0f".format(payslip.netSalary)}"
                        } else {
                            view.findViewById<TextView>(R.id.tvPayslipMonth).text = "No payslip yet"
                            view.findViewById<TextView>(R.id.tvPayslipAmount).text = "—"
                        }

                        // 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()
                }
            }
        }
    }

    private fun monthName(m: Int) = arrayOf(
        "", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ).getOrElse(m) { "" }
}
