package com.b2lmobitech.fieldcloudhrms

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.github.gcacace.signaturepad.views.SignaturePad
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.io.FileOutputStream

class CheckInDetailsActivity : AppCompatActivity() {

    private lateinit var imgPreview: ImageView
    private lateinit var signaturePad: SignaturePad
    private lateinit var btnTakePhoto: Button
    private lateinit var btnSubmit: Button

    private var capturedImageFile: File? = null
    private var signatureFile: File? = null

    private val REQUEST_IMAGE = 2001

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

        imgPreview = findViewById(R.id.imgPreview)
        signaturePad = findViewById(R.id.signaturePad)
        btnTakePhoto = findViewById(R.id.btnTakePhoto)
        btnSubmit = findViewById(R.id.btnSubmit)


        imgPreview.isSaveEnabled = false
        signaturePad.isSaveEnabled = false

        btnTakePhoto.setOnClickListener {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            startActivityForResult(intent, REQUEST_IMAGE)
        }

        btnSubmit.setOnClickListener {
            if (capturedImageFile == null) {
                Toast.makeText(this, "Please capture image", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            saveSignature()
            uploadFiles()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
            val bitmap = data?.extras?.get("data") as Bitmap

            capturedImageFile = File(cacheDir, "checkin_photo.jpg")
            FileOutputStream(capturedImageFile!!).use { out ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)
            }

            imgPreview.setImageURI(Uri.fromFile(capturedImageFile))

        }
    }

    private fun saveSignature() {
        val bitmap = signaturePad.signatureBitmap

        signatureFile = File(cacheDir, "checkin_signature.png")
        val out = FileOutputStream(signatureFile!!)
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
        out.close()
    }

    private fun uploadFiles() {

        val imagePart = MultipartBody.Part.createFormData(
            "image",
            capturedImageFile!!.name,
            capturedImageFile!!.asRequestBody("image/*".toMediaTypeOrNull())
        )

        val signaturePart = MultipartBody.Part.createFormData(
            "signature",
            signatureFile!!.name,
            signatureFile!!.asRequestBody("image/*".toMediaTypeOrNull())
        )

        val sharedPref = getSharedPreferences("login_pref", Context.MODE_PRIVATE)
        val userId = sharedPref.getString("user_id", "") ?: ""
        val orgId = sharedPref.getString("org_id", "") ?: ""

        RetrofitClient.instance.uploadCheckInDetails(orgId, imagePart, signaturePart)
            .enqueue(object : Callback<BasicUploadResponse> {
                override fun onResponse(
                    call: Call<BasicUploadResponse>,
                    response: Response<BasicUploadResponse>
                ) {
                    val res = response.body()

                    if (res != null && res.success) {

                        Log.d("urls","${res.imageurl},${res.signatureurl}")

                        val resultIntent = Intent().apply {
                            putExtra("image_url", res.imageurl)
                            putExtra("signature_url", res.signatureurl)
                        }

                        setResult(Activity.RESULT_OK, resultIntent)
                        finish()

                    } else {
                        Toast.makeText(applicationContext, res?.message ?: "Upload failed", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onFailure(call: Call<BasicUploadResponse>, t: Throwable) {
                    Toast.makeText(applicationContext, "Upload failed", Toast.LENGTH_SHORT).show()
                }
            })
    }
}
