package com.seyalix.hr.ui.muster

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.models.MusterModificationRecord
import kotlinx.coroutines.launch
import kotlinx.coroutines.CancellationException
import java.util.Calendar

class MusterFragment : Fragment() {

    // label shown to user  →  value sent to backend
    private val issueOptions = listOf(
        "Forgot to Sign In" to "forgot_signin",
        "Forgot to Sign Out" to "forgot_signout",
        "Network Issue" to "network_issue",
        "System Problem" to "system_problem",
        "Others" to "others"
    )

    private var selectedDate: String? = null
    private var selectedTime: String? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
        inflater.inflate(R.layout.fragment_muster, container, false)

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

        val tvDate = view.findViewById<TextView>(R.id.tvSelectedDate)
        val tvTime = view.findViewById<TextView>(R.id.tvSelectedTime)
        val spinner = view.findViewById<Spinner>(R.id.spinnerIssueType)
        val etOther = view.findViewById<EditText>(R.id.etOtherReason)
        val btnSubmit = view.findViewById<Button>(R.id.btnSubmitMuster)

        val labels = issueOptions.map { it.first }
        spinner.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, labels)
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, v: View?, position: Int, id: Long) {
                etOther.visibility = if (labels[position] == "Others") View.VISIBLE else View.GONE
            }
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }

        tvDate.setOnClickListener {
            val cal = Calendar.getInstance()
            DatePickerDialog(requireContext(), { _, y, m, d ->
                val date = "%04d-%02d-%02d".format(y, m + 1, d)
                selectedDate = date
                tvDate.text = date
                tvDate.setTextColor(0xFF212121.toInt())
            }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show()
        }

        tvTime.setOnClickListener {
            val cal = Calendar.getInstance()
            TimePickerDialog(requireContext(), { _, h, m ->
                val time = "%02d:%02d:00".format(h, m)
                selectedTime = time
                tvTime.text = "%02d:%02d".format(h, m)
                tvTime.setTextColor(0xFF212121.toInt())
            }, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), true).show()
        }

        btnSubmit.setOnClickListener {
            val date = selectedDate
            val time = selectedTime
            if (date == null) {
                Toast.makeText(context, "Please select a date", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (time == null) {
                Toast.makeText(context, "Please select a time", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val position = spinner.selectedItemPosition
            val issueType = issueOptions[position].second
            val note = etOther.text.toString().trim()
            if (issueType == "others" && note.isBlank()) {
                Toast.makeText(context, "Please describe the issue", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            submitRequest(view, date, time, issueType, note)
        }

        loadHistory(view)
    }

    private fun submitRequest(view: View, date: String, time: String, issueType: String, reason: String) {
        lifecycleScope.launch {
            try {
                val resp = ApiClient.apiService.applyMusterModification(
                    mapOf("date" to date, "time" to time, "issue_type" to issueType, "reason" to reason)
                )
                if (resp.isSuccessful && resp.body()?.success == true) {
                    Toast.makeText(context, "✅ ${resp.body()?.message ?: "Request submitted"}", Toast.LENGTH_LONG).show()
                    // reset form
                    selectedDate = null
                    selectedTime = null
                    view.findViewById<TextView>(R.id.tvSelectedDate).apply {
                        text = "Tap to select a date"
                        setTextColor(0xFF9E9E9E.toInt())
                    }
                    view.findViewById<TextView>(R.id.tvSelectedTime).apply {
                        text = "Tap to select a time"
                        setTextColor(0xFF9E9E9E.toInt())
                    }
                    view.findViewById<EditText>(R.id.etOtherReason).setText("")
                    loadHistory(view)
                } else {
                    Toast.makeText(context, resp.body()?.message ?: "Could not submit request", Toast.LENGTH_LONG).show()
                }
            } 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 loadHistory(view: View) {
        view.findViewById<TextView>(R.id.btnRefreshMuster).setOnClickListener { loadHistory(view) }

        lifecycleScope.launch {
            try {
                val resp = ApiClient.apiService.getMyMusterModifications()
                if (resp.isSuccessful && resp.body()?.success == true) {
                    val records = resp.body()!!.data ?: emptyList()
                    activity?.runOnUiThread { renderHistory(view, records) }
                }
            } 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 renderHistory(view: View, records: List<MusterModificationRecord>) {
        val lv = view.findViewById<ListView>(R.id.lvMusterRequests)
        lv.adapter = object : ArrayAdapter<MusterModificationRecord>(requireContext(), 0, records) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val row = convertView ?: layoutInflater.inflate(R.layout.item_muster_row, parent, false)
                val r = records[position]

                val label = issueOptions.find { it.second == r.issueType }?.first ?: r.issueType
                row.findViewById<TextView>(R.id.tvRowDate).text = "${r.date}  ${r.time?.take(5) ?: ""}"
                row.findViewById<TextView>(R.id.tvRowIssue).text =
                    if (!r.reason.isNullOrBlank()) "$label — ${r.reason}" else label

                val tvStatus = row.findViewById<TextView>(R.id.tvRowStatus)
                tvStatus.text = r.status.replaceFirstChar { it.uppercase() }
                tvStatus.setBackgroundResource(
                    when (r.status.lowercase()) {
                        "approved" -> R.drawable.badge_green
                        "rejected" -> R.drawable.badge_red
                        "pending" -> R.drawable.badge_orange
                        else -> R.drawable.badge_gray
                    }
                )
                return row
            }
        }

        if (records.isEmpty()) {
            Toast.makeText(context, "No muster modification requests yet", Toast.LENGTH_SHORT).show()
        }
    }
}
