package com.seyalix.hr.ui.reports

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.utils.PrefsManager
import kotlinx.coroutines.launch
import kotlinx.coroutines.CancellationException
import java.util.Calendar

class ReportsFragment : Fragment() {

    private lateinit var prefs: PrefsManager

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

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

        val cal   = Calendar.getInstance()
        val month = cal.get(Calendar.MONTH) + 1
        val year  = cal.get(Calendar.YEAR)

        view.findViewById<TextView>(R.id.tvReportTitle).text =
            "Team Attendance Report – ${monthName(month)} $year"

        // Team today
        view.findViewById<Button>(R.id.btnTodayTeam).setOnClickListener {
            loadTeamToday(view)
        }

        // Monthly report
        view.findViewById<Button>(R.id.btnMonthlyReport).setOnClickListener {
            loadMonthlyReport(view, month, year)
        }

        // Load today by default
        loadTeamToday(view)
    }

    private fun loadTeamToday(view: View) {
        val today = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault())
            .format(java.util.Date())
        lifecycleScope.launch {
            try {
                val resp = ApiClient.apiService.getTeamAttendance(today)
                if (resp.isSuccessful && resp.body()?.success == true) {
                    val team = resp.body()!!.data ?: emptyList()
                    val items = team.map { t ->
                        "${t.empCode}  ${t.firstName} ${t.lastName}\n" +
                        "Status: ${t.status.uppercase()}  In: ${t.checkIn ?: "—"}  Out: ${t.checkOut ?: "—"}"
                    }
                    activity?.runOnUiThread {
                        view.findViewById<ListView>(R.id.lvReport).adapter =
                            ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, items)
                        // Summary count
                        val present = team.count { it.status == "present" || it.status == "late" }
                        val absent  = team.count { it.status == "absent" }
                        view.findViewById<TextView>(R.id.tvReportSummary).text =
                            "Present: $present  |  Absent: $absent  |  Total: ${team.size}"
                    }
                }
            } catch (e: CancellationException) {
                throw e  // normal when the screen changes mid-request — not a real error
            } catch (e: Exception) {
                Toast.makeText(context, "Error: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun loadMonthlyReport(view: View, month: Int, year: Int) {
        lifecycleScope.launch {
            try {
                val resp = ApiClient.apiService.getTeamReport(month, year)
                if (resp.isSuccessful && resp.body()?.success == true) {
                    val data = resp.body()!!.data ?: emptyList()
                    val items = data.map { row ->
                        val name    = "${row["first_name"]} ${row["last_name"]}"
                        val code    = row["emp_code"] ?: ""
                        val present = row["present"] ?: 0
                        val absent  = row["absent"]  ?: 0
                        val late    = row["late"]     ?: 0
                        "$code  $name\nPresent: $present  Absent: $absent  Late: $late"
                    }
                    activity?.runOnUiThread {
                        view.findViewById<ListView>(R.id.lvReport).adapter =
                            ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, items)
                        view.findViewById<TextView>(R.id.tvReportSummary).text =
                            "Monthly Report – ${data.size} employees"
                    }
                }
            } catch (e: CancellationException) {
                throw e  // normal when the screen changes mid-request — not a real error
            } catch (e: Exception) {
                Toast.makeText(context, "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")[m]
}
