package com.example.projekta

import android.Manifest
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.Base64
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.PermissionChecker
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.projekta.databinding.ActivityProfileBinding
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.util.Calendar

class ProfileActivity : AppCompatActivity() {

    private lateinit var binding: ActivityProfileBinding
    private var bitmapImage: Bitmap? = null

    // ===============================
    // PILIH FOTO GALERI
    // ===============================
    private val pickImage =
        registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->

            if (uri != null) {

                val inputStream = contentResolver.openInputStream(uri)
                bitmapImage = BitmapFactory.decodeStream(inputStream)

                binding.imgProfile.setImageBitmap(bitmapImage)
            }
        }

    // ===============================
    // CAMERA
    // ===============================
    private val takePhoto =
        registerForActivityResult(ActivityResultContracts.TakePicturePreview()) { bitmap ->

            if (bitmap != null) {
                bitmapImage = bitmap
                binding.imgProfile.setImageBitmap(bitmap)
            }
        }

    // ===============================
    // PERMISSION CAMERA
    // ===============================
    private val requestCameraPermission =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->

            if (granted) {
                takePhoto.launch(null)
            } else {
                Toast.makeText(this, "Izin kamera ditolak", Toast.LENGTH_SHORT).show()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityProfileBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnBack.setOnClickListener {
            finish()
        }

        loadProfile()

        binding.imgProfile.setOnClickListener {
            showImagePickerDialog()
        }

        binding.etTanggal.setOnClickListener {
            showDatePicker()
        }

        binding.btnUpdate.setOnClickListener {
            updateProfile()
        }
    }

    // ===============================
    // LOAD PROFILE
    // ===============================
    private fun loadProfile() {

        val url = "http://192.168.43.191/projekta/profile.php"

        val request = object : StringRequest(
            Method.POST,
            url,
            { response ->

                try {

                    val json = JSONObject(response)

                    val nama = json.optString("nama")
                    val email = json.optString("email")
                    val phone = json.optString("phone")
                    val tanggal = json.optString("tanggal")
                    val foto = json.optString("foto").trim()

                    binding.etNama.setText(nama)
                    binding.etEmail.setText(email)
                    binding.etPhone.setText(phone)
                    binding.etTanggal.setText(tanggal)

                    binding.txtName.text = nama
                    binding.txtEmail.text = email

                    // FOTO
                    if (foto.isNotEmpty()) {

                        val decoded = Base64.decode(foto, Base64.DEFAULT)

                        val bitmap = BitmapFactory.decodeByteArray(
                            decoded,
                            0,
                            decoded.size
                        )

                        if (bitmap != null) {
                            binding.imgProfile.setImageBitmap(bitmap)
                        }
                    }

                } catch (e: Exception) {
                    Toast.makeText(this, "Format data error", Toast.LENGTH_SHORT).show()
                }

            },
            {
                Toast.makeText(this, "Gagal koneksi server", Toast.LENGTH_SHORT).show()
            }

        ) {

            override fun getParams(): MutableMap<String, String> {

                val params = HashMap<String, String>()

                val email = getSharedPreferences(
                    "LOGIN",
                    Context.MODE_PRIVATE
                ).getString("email", "")

                params["email"] = email ?: ""

                return params
            }
        }

        Volley.newRequestQueue(this).add(request)
    }

    // ===============================
    // UPDATE PROFILE
    // ===============================
    private fun updateProfile() {

        val url = "http://192.168.43.191/projekta/update_profile.php"

        val request = object : StringRequest(
            Method.POST,
            url,
            { response ->

                if (response.contains("success")) {

                    val namaBaru = binding.etNama.text.toString().trim()

                    val pref = getSharedPreferences(
                        "USER_DATA",
                        Context.MODE_PRIVATE
                    )

                    val editor = pref.edit()

                    editor.putString("nama", namaBaru)

                    // simpan foto utk sidebar
                    if (bitmapImage != null) {

                        val baos = ByteArrayOutputStream()

                        bitmapImage!!.compress(
                            Bitmap.CompressFormat.JPEG,
                            80,
                            baos
                        )

                        val base64Foto = Base64.encodeToString(
                            baos.toByteArray(),
                            Base64.NO_WRAP
                        )

                        editor.putString("foto", base64Foto)
                    }

                    editor.apply()

                    binding.txtName.text = namaBaru

                    Toast.makeText(
                        this,
                        "Profil berhasil diperbarui",
                        Toast.LENGTH_SHORT
                    ).show()

                } else {

                    Toast.makeText(
                        this,
                        "Gagal update",
                        Toast.LENGTH_SHORT
                    ).show()
                }

            },
            {
                Toast.makeText(this, "Error server", Toast.LENGTH_SHORT).show()
            }

        ) {

            override fun getParams(): MutableMap<String, String> {

                val params = HashMap<String, String>()

                val email = getSharedPreferences(
                    "LOGIN",
                    Context.MODE_PRIVATE
                ).getString("email", "")

                params["email"] = email ?: ""
                params["nama"] = binding.etNama.text.toString().trim()
                params["phone"] = binding.etPhone.text.toString().trim()
                params["tanggal"] = binding.etTanggal.text.toString().trim()

                if (bitmapImage != null) {

                    val baos = ByteArrayOutputStream()

                    bitmapImage!!.compress(
                        Bitmap.CompressFormat.JPEG,
                        80,
                        baos
                    )

                    params["foto"] = Base64.encodeToString(
                        baos.toByteArray(),
                        Base64.NO_WRAP
                    )

                } else {
                    params["foto"] = ""
                }

                return params
            }
        }

        Volley.newRequestQueue(this).add(request)
    }

    // ===============================
    // DATE PICKER
    // ===============================
    private fun showDatePicker() {

        val c = Calendar.getInstance()

        DatePickerDialog(
            this,
            { _, y, m, d ->

                binding.etTanggal.setText(
                    "$d/${m + 1}/$y"
                )

            },
            c.get(Calendar.YEAR),
            c.get(Calendar.MONTH),
            c.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    // ===============================
    // PILIH FOTO
    // ===============================
    private fun showImagePickerDialog() {

        val pilihan = arrayOf("Galeri", "Kamera")

        AlertDialog.Builder(this)
            .setTitle("Pilih Foto")
            .setItems(pilihan) { _, which ->

                when (which) {
                    0 -> pickImage.launch("image/*")
                    1 -> openCamera()
                }

            }
            .show()
    }

    // ===============================
    // OPEN CAMERA
    // ===============================
    private fun openCamera() {

        if (
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) == PermissionChecker.PERMISSION_GRANTED
        ) {
            takePhoto.launch(null)
        } else {
            requestCameraPermission.launch(
                Manifest.permission.CAMERA
            )
        }
    }
}