package com.b2lmobitech.fieldcloudhrms

import android.app.DatePickerDialog
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.b2lmobitech.fieldcloudhrms.databinding.ActivityEditProfileBinding
import com.bumptech.glide.Glide
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*

class EditProfileActivity : AppCompatActivity() {

    private lateinit var binding: ActivityEditProfileBinding
    private lateinit var peopleId: String
    private lateinit var orgId: String
    private var profileImageUri: Uri? = null
    private var aadharImageUri: Uri? = null
    private var selectedCountryId = ""
    private var selectedStateId = ""
    private var selectedCityId = ""



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

        val pref = getSharedPreferences("login_pref", Context.MODE_PRIVATE)
        peopleId = pref.getString("user_id", "")!!
        orgId = pref.getString("org_id", "")!!

        loadProfile()

        binding.btnBack.setOnClickListener { finish() }
        binding.etDob.setOnClickListener { openDatePicker() }

        binding.btnSave.setOnClickListener { updateProfile() }

        binding.btnProfileImage.setOnClickListener {
            profileImageLauncher.launch("image/*")
        }

        binding.btnAadharImage.setOnClickListener {
            aadharImageLauncher.launch("image/*")
        }


    }

    private val profileImageLauncher =
        registerForActivityResult(ActivityResultContracts.GetContent()) {
            profileImageUri = it
            binding.imgProfile.setImageURI(it)
        }

    private val aadharImageLauncher =
        registerForActivityResult(ActivityResultContracts.GetContent()) {
            aadharImageUri = it
            binding.imgAadhar.setImageURI(it)
        }


    private fun loadProfile() {
        RetrofitClient.instance.getProfile(peopleId, orgId)
            .enqueue(object : Callback<ProfileResponse> {
                override fun onResponse(
                    call: Call<ProfileResponse>,
                    response: Response<ProfileResponse>
                ) {
                    if (response.isSuccessful && response.body()?.success == true) {
                        val d = response.body()!!.data
                        binding.etAddress.setText(d.address)
//                        binding.etCity.setText(d.city_name)
//                        binding.etState.setText(d.state_name)
//                        binding.etCountry.setText(d.country_name)
                        binding.etMobile.setText(d.mobile_number)
                        binding.etDob.setText(d.dob)

                        loadCountries(
                            d.country_name,
                            d.state_name,
                            d.city_name
                        )
                        // Marital Status
                        if (d.marital_status.isNullOrBlank()) {
                            binding.spMarital.setSelection(0)
                        } else {
                            val maritalIndex = resources.getStringArray(R.array.marital_status)
                                .indexOf(d.marital_status)
                            binding.spMarital.setSelection(if (maritalIndex >= 0) maritalIndex else 0)
                        }

                        // Blood Group
                        if (d.blood_group.isNullOrBlank()) {
                            binding.spBlood.setSelection(0)
                        } else {
                            val bloodIndex = resources.getStringArray(R.array.blood_groups)
                                .indexOf(d.blood_group)
                            binding.spBlood.setSelection(if (bloodIndex >= 0) bloodIndex else 0)
                        }

                        Glide.with(this@EditProfileActivity)
                            .load("https://processflow.in/HRMS/"+d.photo_image_path)
                            .placeholder(R.drawable.placeholder)
                            .into(binding.imgProfile)

                        Glide.with(this@EditProfileActivity)
                            .load("https://processflow.in/HRMS/"+d.aadhar_photo_path)
                            .placeholder(R.drawable.placeholder)
                            .into(binding.imgAadhar)

                    }
                }

                override fun onFailure(call: Call<ProfileResponse>, t: Throwable) {
                    Toast.makeText(this@EditProfileActivity, t.message, Toast.LENGTH_SHORT).show()
                }
            })
    }

    private fun updateProfile() {

        fun textBody(value: String) =
            value.toRequestBody("text/plain".toMediaType())

        val profilePart = profileImageUri?.let {
            val file = FileUtil.from(this, it)
            MultipartBody.Part.createFormData(
                "profile_image", file.name,
                file.asRequestBody("image/*".toMediaType())
            )
        }

        val aadharPart = aadharImageUri?.let {
            val file = FileUtil.from(this, it)
            MultipartBody.Part.createFormData(
                "aadhar_image", file.name,
                file.asRequestBody("image/*".toMediaType())
            )
        }
        val maritalValue =
            if (binding.spMarital.selectedItemPosition == 0) ""
            else binding.spMarital.selectedItem.toString()

        val bloodValue =
            if (binding.spBlood.selectedItemPosition == 0) ""
            else binding.spBlood.selectedItem.toString()


        RetrofitClient.instance.updateProfile(
            textBody(peopleId),
            textBody(orgId),
            textBody(binding.etAddress.text.toString()),
            textBody(binding.etMobile.text.toString()),
            textBody(binding.etDob.text.toString()),
            textBody(maritalValue),
            textBody(bloodValue),
            textBody(selectedCityId),
            textBody(selectedStateId),
            textBody(selectedCountryId),
            textBody(binding.etAadhar.text.toString()),
            textBody(binding.etPan.text.toString()),
            profilePart,
            aadharPart
        ).enqueue(object : Callback<SimpleResponse> {
            override fun onResponse(call: Call<SimpleResponse>, response: Response<SimpleResponse>) {
                Toast.makeText(this@EditProfileActivity, "Profile Updated", Toast.LENGTH_SHORT).show()
                finish()
            }

            override fun onFailure(call: Call<SimpleResponse>, t: Throwable) {
                Toast.makeText(this@EditProfileActivity, t.message, Toast.LENGTH_SHORT).show()
            }
        })
    }


    private fun openDatePicker() {
        val cal = Calendar.getInstance()
        DatePickerDialog(
            this,
            { _, y, m, d ->
                val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                cal.set(y, m, d)
                binding.etDob.setText(sdf.format(cal.time))
            },
            cal.get(Calendar.YEAR),
            cal.get(Calendar.MONTH),
            cal.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    private fun getBloodIndex(bg: String?): Int {
        val list = resources.getStringArray(R.array.blood_groups)
        return list.indexOf(bg).takeIf { it >= 0 } ?: 0
    }

    private fun loadCountries(
        savedCountryName: String?,
        savedStateName: String?,
        savedCityName: String?
    ) {
        RetrofitClient.instance.getCountries()
            .enqueue(object : Callback<ListResponse<Country>> {

                override fun onResponse(
                    call: Call<ListResponse<Country>>,
                    response: Response<ListResponse<Country>>
                ) {
                    val list = response.body()?.data ?: return

                    val countryNames = mutableListOf("Select Country")
                    countryNames.addAll(list.map { it.country })

                    binding.spCountry.adapter = ArrayAdapter(
                        this@EditProfileActivity,
                        android.R.layout.simple_spinner_dropdown_item,
                        countryNames
                    )

                    //  Default selection
                    binding.spCountry.setSelection(0)
                    selectedCountryId = ""

                    //  If server value exists, auto-select
                    val index = list.indexOfFirst { it.country == savedCountryName }
                    if (index >= 0) {
                        binding.spCountry.setSelection(index + 1)
                        selectedCountryId = list[index].id
                        loadStates(selectedCountryId, savedStateName, savedCityName)
                    }

                    binding.spCountry.onItemSelectedListener =
                        object : AdapterView.OnItemSelectedListener {

                            override fun onItemSelected(
                                parent: AdapterView<*>,
                                view: View?,
                                pos: Int,
                                id: Long
                            ) {
                                if (pos == 0) {
                                    selectedCountryId = ""
                                    clearStateCity()
                                    return
                                }

                                selectedCountryId = list[pos - 1].id
                                loadStates(selectedCountryId, null, null)
                            }

                            override fun onNothingSelected(parent: AdapterView<*>) {}
                        }
                }

                override fun onFailure(call: Call<ListResponse<Country>>, t: Throwable) {}
            })
    }

    private fun loadStates(
        countryId: String,
        savedStateName: String?,
        savedCityName: String?
    ) {
        RetrofitClient.instance.getStates(countryId)
            .enqueue(object : Callback<ListResponse<State>> {

                override fun onResponse(
                    call: Call<ListResponse<State>>,
                    response: Response<ListResponse<State>>
                ) {
                    val list = response.body()?.data ?: return

                    val stateNames = mutableListOf("Select State")
                    stateNames.addAll(list.map { it.state })

                    binding.spState.adapter = ArrayAdapter(
                        this@EditProfileActivity,
                        android.R.layout.simple_spinner_dropdown_item,
                        stateNames
                    )

                    binding.spState.setSelection(0)
                    selectedStateId = ""

                    val index = list.indexOfFirst { it.state == savedStateName }
                    if (index >= 0) {
                        binding.spState.setSelection(index + 1)
                        selectedStateId = list[index].id
                        loadCities(selectedStateId, savedCityName)
                    }

                    binding.spState.onItemSelectedListener =
                        object : AdapterView.OnItemSelectedListener {

                            override fun onItemSelected(
                                parent: AdapterView<*>,
                                view: View?,
                                pos: Int,
                                id: Long
                            ) {
                                if (pos == 0) {
                                    selectedStateId = ""
                                    clearCity()
                                    return
                                }

                                selectedStateId = list[pos - 1].id
                                loadCities(selectedStateId, null)
                            }

                            override fun onNothingSelected(parent: AdapterView<*>) {}
                        }
                }

                override fun onFailure(call: Call<ListResponse<State>>, t: Throwable) {}
            })
    }

    private fun loadCities(
        stateId: String,
        savedCityName: String?
    ) {
        RetrofitClient.instance.getCities(stateId)
            .enqueue(object : Callback<ListResponse<City>> {

                override fun onResponse(
                    call: Call<ListResponse<City>>,
                    response: Response<ListResponse<City>>
                ) {
                    val list = response.body()?.data ?: return

                    val cityNames = mutableListOf("Select City")
                    cityNames.addAll(list.map { it.city })

                    binding.spCity.adapter = ArrayAdapter(
                        this@EditProfileActivity,
                        android.R.layout.simple_spinner_dropdown_item,
                        cityNames
                    )

                    binding.spCity.setSelection(0)
                    selectedCityId = ""

                    val index = list.indexOfFirst { it.city == savedCityName }
                    if (index >= 0) {
                        binding.spCity.setSelection(index + 1)
                        selectedCityId = list[index].id
                    }

                    binding.spCity.onItemSelectedListener =
                        object : AdapterView.OnItemSelectedListener {

                            override fun onItemSelected(
                                parent: AdapterView<*>,
                                view: View?,
                                pos: Int,
                                id: Long
                            ) {
                                selectedCityId =
                                    if (pos == 0) "" else list[pos - 1].id
                            }

                            override fun onNothingSelected(parent: AdapterView<*>) {}
                        }
                }

                override fun onFailure(call: Call<ListResponse<City>>, t: Throwable) {}
            })
    }

    private fun clearStateCity() {
        binding.spState.adapter = null
        binding.spCity.adapter = null
        selectedStateId = ""
        selectedCityId = ""
    }

    private fun clearCity() {
        binding.spCity.adapter = null
        selectedCityId = ""
    }


}
