package com.b2lmobitech.fieldcloudhrms

import android.app.DatePickerDialog
import android.content.Context
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ImageView
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.b2lmobitech.fieldcloudhrms.R
import java.util.*

class AddTravelActivity : AppCompatActivity() {

    private lateinit var tvDepartureDate: TextView
    private lateinit var tvArrivalDate: TextView
    private lateinit var tvEmpId: EditText
    private lateinit var spBillable: Spinner
    private lateinit var etPlace: EditText
    private lateinit var etPurpose: EditText
    private lateinit var etExpense: EditText
    private lateinit var etDuration: EditText
    private lateinit var etCustomer: EditText
    private lateinit var btnSubmit: TextView


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_travel)


        val sharedPref = getSharedPreferences("login_pref", Context.MODE_PRIVATE)

        val userId = sharedPref.getString("user_id", "") ?: ""
        val orgId = sharedPref.getString("org_id", "") ?: ""

        tvEmpId = findViewById(R.id.tvEmpId)
        etPlace = findViewById(R.id.etPlace)
        etPurpose = findViewById(R.id.etPurpose)
        etDuration = findViewById(R.id.etDuration)
        etCustomer = findViewById(R.id.etCustomer)
        etExpense = findViewById(R.id.etExpense)


        tvDepartureDate = findViewById(R.id.tvDepartureDate)
        tvArrivalDate = findViewById(R.id.tvArrivalDate)

        tvEmpId.setText(userId)
        tvEmpId.isFocusable = false
        tvEmpId.isClickable = false

        tvDepartureDate.setOnClickListener {
            showDatePicker(tvDepartureDate)
        }

        tvArrivalDate.setOnClickListener {
            showDatePicker(tvArrivalDate)
        }

        findViewById<TextView>(R.id.btnSubmit).setOnClickListener {
            Toast.makeText(this, "Travel Request Submitted", Toast.LENGTH_SHORT).show()
            finish()
        }

        findViewById<TextView>(R.id.btnCancel).setOnClickListener {
            finish()
        }

        spBillable = findViewById(R.id.spBillable)

        val billableList = listOf("Select", "Yes", "No")

        val adapter = ArrayAdapter(
            this,
            R.layout.spinner_item,
            billableList
        )
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spBillable.adapter = adapter

        btnSubmit = findViewById(R.id.btnSubmit)

        btnSubmit.setOnClickListener {

            val employeeId = tvEmpId.text.toString().trim()
            val place = etPlace.text.toString().trim()
            val departure = tvDepartureDate.text.toString().trim()
            val arrival = tvArrivalDate.text.toString().trim()
            val purpose = etPurpose.text.toString().trim()
            val duration = etDuration.text.toString().trim()
            val expense = etExpense.text.toString().trim()
            val billable = spBillable.selectedItem.toString()
            val customer = etCustomer.text.toString().trim()

            if (place.isEmpty() || billable == "Select") {
                Toast.makeText(this, "Please fill required fields", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            RetrofitClient.instance.addTravelRequest(
                employeeId,
                orgId,
                place,
                departure,
                arrival,
                purpose,
                duration,
                expense,
                billable,
                customer
            ).enqueue(object : retrofit2.Callback<ApiResponse> {

                override fun onResponse(
                    call: retrofit2.Call<ApiResponse>,
                    response: retrofit2.Response<ApiResponse>
                ) {
                    if (response.isSuccessful && response.body()?.success == true) {
                        Toast.makeText(this@AddTravelActivity,
                            response.body()?.message ?: "Success",
                            Toast.LENGTH_SHORT).show()
                        finish()
                    } else {
                        Toast.makeText(this@AddTravelActivity,
                            "Failed to submit",
                            Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: retrofit2.Call<ApiResponse>, t: Throwable) {
                    Toast.makeText(this@AddTravelActivity,
                        "Server error",
                        Toast.LENGTH_SHORT).show()
                }
            })
        }

        findViewById<ImageView>(R.id.btnBack).setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        findViewById<TextView>(R.id.btnCancel).setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }


    }

    private fun showDatePicker(target: TextView) {
        val cal = Calendar.getInstance()
        DatePickerDialog(
            this,
            { _, year, month, day ->
                target.text = "$day-${month + 1}-$year"
            },
            cal.get(Calendar.YEAR),
            cal.get(Calendar.MONTH),
            cal.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

}
