package com.nivesh.production.niveshfd.partnerOnBoarding.ui.fragments1

import android.Manifest
import android.app.Activity
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Switch
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import com.google.android.material.button.MaterialButton
import com.nivesh.production.niveshfd.R
import com.nivesh.production.niveshfd.databinding.FragmentGetStartedBinding
import com.nivesh.production.niveshfd.fd.db.PreferenceManager
import com.nivesh.production.niveshfd.fd.ui.activity.BaseActivity
import com.nivesh.production.niveshfd.fd.util.Common.Companion.showDialogWithTwoButtons
import com.nivesh.production.niveshfd.partnerOnBoarding.ui.activities1.SignUpActivity
import java.io.File
import java.io.FileDescriptor
import java.io.IOException

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

class GetStartedFragment : BaseFragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    private var _binding: FragmentGetStartedBinding? = null
    private val binding get() = _binding!!
    private var latestTmpUri: Uri? = null
    private var takeImageResult: ActivityResultLauncher<Uri>? = null
    private var selectImageIntent: ActivityResultLauncher<String>? = null
    private var bitmap: Bitmap? = null
    private val mainPANUpload: Int = 1
    private val mainPhotoUpload: Int = 2
    private val firstDocUpload: Int = 3
    private val secondDocUpload: Int = 4
    private var actionType: Int = -1

    private val listArray = ArrayList<String>()
    private val permissions = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    private val requestCameraPermission = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            takeImage()
        } else {
            showDialogWithTwoButtons(
                (activity as SignUpActivity), getString(R.string.cameraPermission), getString(
                    R.string.permissionRequired
                )
            )
        }
    }

    private val requestGalleryPermission = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permission ->
        if (!permission.containsValue(false)) {
            selectImageIntent?.launch("image/*")
        } else {
            showDialogWithTwoButtons(
                (activity as SignUpActivity),
                getString(R.string.galleryPermission),
                getString(
                    R.string.permissionsRequired
                )
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        // Inflate the layout for this fragment
        _binding = FragmentGetStartedBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()

        selectImageIntent = registerForActivityResult(ActivityResultContracts.GetContent())
        { uri: Uri? ->
            if (uri != null) {
                bitmap = uriToBitmap(uri)
//                uploadDocument(uri, "g")
            }
        }

        takeImageResult =
            registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccess ->
                if (isSuccess) {
                    latestTmpUri?.let { uri ->
//                        uploadDocument(uri, "c")
                    }
                }
            }
    }

    private fun uriToBitmap(selectedFileUri: Uri): Bitmap? {
        try {
            val parcelFileDescriptor =
                requireActivity().contentResolver.openFileDescriptor(selectedFileUri, "r")
            val fileDescriptor: FileDescriptor = parcelFileDescriptor!!.fileDescriptor
            val image = BitmapFactory.decodeFileDescriptor(fileDescriptor)
            parcelFileDescriptor.close()
            return image
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

    private fun init() {

        binding.btnNext.setOnClickListener {
            replaceFragment(
                activity as BaseActivity,
                R.id.signUpContainer,
                AlmostThereFragment(),
                "GET STARTED",
                true
            )
        }

        listArray.add("Aadhaar")
        listArray.add("Passport")
        listArray.add("Driving Licenses")
        listArray.add("Voter Id")

        val arrayAdapter = ArrayAdapter(activity as SignUpActivity, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,listArray)
        binding.spDocType.setAdapter(arrayAdapter)

        binding.spDocType.setOnItemClickListener{ _, _, position, _ ->
//            setVisibility(listArray[position])
        }

        binding.uploadFront.setOnClickListener {
            actionType = mainPANUpload
            selectImage()
        }
    }

    private fun selectImage() {
        val builder = AlertDialog.Builder(
            activity as SignUpActivity
        )
        builder.setTitle(getString(R.string.addPhoto))
        builder.setItems(
            arrayOf(
                getString(R.string.takePhoto),
                getString(R.string.chooseFromGallery),
                getString(R.string.cancel)
            )
        ) { dialog: DialogInterface, pos ->
            when (pos) {
                0 -> {
                    if (hasPermissions(
                            activity as SignUpActivity,
                            Manifest.permission.CAMERA
                        )
                    ) {
                        takeImage()
                    } else {
                        onClickRequestPermission()
                    }
                    dialog.dismiss()
                }
                1 -> {
                    if (hasPermissions(activity as SignUpActivity, *permissions)) {
                        selectImageIntent?.launch("image/*")
                    } else {
                        requestGalleryPermission.launch(permissions)
                    }
                    dialog.dismiss()
                }
                else -> {
                    dialog.dismiss()
                }
            }
        }
        builder.show()
    }

    private fun onClickRequestPermission() {
        when {
            ContextCompat.checkSelfPermission(
                activity as SignUpActivity,
                Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED -> {

            }

            ActivityCompat.shouldShowRequestPermissionRationale(
                activity as SignUpActivity,
                Manifest.permission.CAMERA
            ) -> {
                requestCameraPermission.launch(
                    Manifest.permission.CAMERA
                )
            }

            else -> {
                requestCameraPermission.launch(
                    Manifest.permission.CAMERA
                )
            }
        }
    }

    private fun hasPermissions(activity: Activity, vararg permissions: String?): Boolean {
        for (permission in permissions) {
            if (ActivityCompat.checkSelfPermission(
                    activity,
                    permission!!
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }

//    private fun setVisibility(s: String) {
//        if(s.contains("Aadhaar")){
//            binding.txtFront.visibility = View.VISIBLE
//            binding.uploadFront.visibility = View.VISIBLE
//            binding.txtBack.visibility = View.VISIBLE
//            binding.uploadViewBack.visibility = View.VISIBLE
//        }else{
//            binding.txtFront.visibility = View.VISIBLE
//            binding.uploadFront.visibility = View.VISIBLE
//            binding.txtBack.visibility = View.GONE
//            binding.uploadViewBack.visibility = View.GONE
//        }
//    }

    private fun takeImage() {
        lifecycleScope.launchWhenStarted {
            getTmpFileUri().let { uri ->
                latestTmpUri = uri
                takeImageResult?.launch(uri)
            }
        }
    }

//    private fun uploadDocument(uri: Uri, type: String) {
//        when (actionType) {
//            mainPANUpload -> {
//                binding.ivPan.visibility = View.VISIBLE
//                val fileDir: File = requireActivity().cacheDir
//                val fileExtension = File(fileDir.toString().plus("/").plus(getFileName(uri)))
//                panFileExt = getFileExtension(getFileName(uri))
//                val size: Double = Common.getFileSizeInMB(fileExtension.length())
//                if (size < 5) {
//                    if (type == "c") encodedPANBase64(fileExtension)
//                    else panString = bitmap?.let { ImageUtil.convert(it) }.toString()
//                } else {
//                    panString = ""
//                    panFileExt = ""
//                }
//            }
//            mainPhotoUpload -> {
//                binding.ivPhotograph.visibility = View.VISIBLE
//                val fileDir: File = requireActivity().cacheDir
//                val fileExtension = File(fileDir.toString().plus("/").plus(getFileName(uri)))
//                photoFileExt = getFileExtension(getFileName(uri))
//                val size: Double = Common.getFileSizeInMB(fileExtension.length())
//                if (size < 5) {
//                    if (type == "c") encodedPhotoBase64(fileExtension)
//                    else photoString = bitmap?.let { ImageUtil.convert(it) }.toString()
//                } else {
//                    photoString = ""
//                    photoFileExt = ""
//                }
//            }
//            firstDocUpload -> {
//                binding.ivAadharFront.visibility = View.VISIBLE
//                val fileDir: File = requireActivity().cacheDir
//                val fileExtension = File(fileDir.toString().plus("/").plus(getFileName(uri)))
//                doc1FileExt = getFileExtension(getFileName(uri))
//                val size: Double = Common.getFileSizeInMB(fileExtension.length())
//                if (size < 5) {
//                    if (type == "c") encodedUpload1Base64(fileExtension)
//                    else docString = bitmap?.let { ImageUtil.convert(it) }.toString()
//                } else {
//                    docString = ""
//                    doc1FileExt = ""
//                }
//            }
//            else -> {
//                binding.ivAadharBack.visibility = View.VISIBLE
//                val fileDir: File = requireActivity().cacheDir
//                val fileExtension = File(fileDir.toString().plus("/").plus(getFileName(uri)))
//                doc2fileExt = getFileExtension(getFileName(uri))
//                val size: Double = Common.getFileSizeInMB(fileExtension.length())
//                if (size < 5) {
//                    if (type == "c") encodedFileToBase64(fileExtension)
//                    else docString2 = bitmap?.let { ImageUtil.convert(it) }.toString()
//                } else {
//                    docString2 = ""
//                    doc2fileExt = ""
//                }
//            }
//        }
//    }

    private fun getTmpFileUri(): Uri {
        val tmpFile =
            File.createTempFile("tmp_image_file", ".png", requireActivity().cacheDir).apply {
                createNewFile()
                deleteOnExit()
            }

        return FileProvider.getUriForFile(
            requireActivity(), PreferenceManager(activity as SignUpActivity).getAppId().plus(".provider"), tmpFile)
    }
}