package com.b2lmobitech.fieldcloudhrms

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.b2lmobitech.fieldcloudhrms.databinding.ActivityTimesheetDetailsBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class TimesheetDetailsActivity : AppCompatActivity() {

    private lateinit var binding: ActivityTimesheetDetailsBinding
    private val api by lazy { RetrofitClient.instance }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityTimesheetDetailsBinding.inflate(layoutInflater)
        setContentView(binding.root)

//        binding.btnBack.setOnClickListener { finish() }

        val timesheetId = intent.getStringExtra("timesheet_id") ?: ""

        if (timesheetId.isEmpty()) {
            Toast.makeText(this, "Invalid timesheet", Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        loadTimesheetDetails(timesheetId)
    }

    private fun loadTimesheetDetails(timesheetId: String) {

        api.getTimesheetDetails(timesheetId)
            .enqueue(object : Callback<TimesheetDetailsResponse> {
                override fun onResponse(
                    call: Call<TimesheetDetailsResponse>,
                    response: Response<TimesheetDetailsResponse>
                ) {
                    if (response.isSuccessful && response.body() != null) {
                        val data = response.body()!!
                        setDetails(data)
                    } else {
                        Toast.makeText(this@TimesheetDetailsActivity, "No data found", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: Call<TimesheetDetailsResponse>, t: Throwable) {
                    Toast.makeText(this@TimesheetDetailsActivity, "Error: ${t.message}", Toast.LENGTH_SHORT).show()
                    Log.e("Error", t.message.toString())
                }
            })
    }

    private fun setDetails(data: TimesheetDetailsResponse) {

        binding.txtActivity.text = data.activity
        binding.txtDate.text = data.timesheetdate
        binding.txtStartTime.text = data.starttime
        binding.txtEndTime.text = data.endtime
        binding.txtDescription.text = data.description

        // Attachments
        binding.rvAttachments.layoutManager = LinearLayoutManager(this)
        binding.rvAttachments.adapter = TimesheetAttachmentsAdapter(data.attachments)
    }
}
