package com.all.pdfreader.pro.app.ui.dialog

import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.DialogListMoreBinding
import com.all.pdfreader.pro.app.model.PdfPickerSource
import com.all.pdfreader.pro.app.model.PrintResult
import com.all.pdfreader.pro.app.model.RenameType
import com.all.pdfreader.pro.app.room.entity.PdfDocumentEntity
import com.all.pdfreader.pro.app.ui.act.MergePdfActivity
import com.all.pdfreader.pro.app.ui.act.PdfPickerActivity
import com.all.pdfreader.pro.app.ui.act.PdfToImageActivity
import com.all.pdfreader.pro.app.ui.act.PdfViewActivity
import com.all.pdfreader.pro.app.ui.act.SplitPdfActivity
import com.all.pdfreader.pro.app.ui.fragment.FavoriteFrag
import com.all.pdfreader.pro.app.ui.fragment.HomeFrag
import com.all.pdfreader.pro.app.ui.fragment.RecentlyFrag
import com.all.pdfreader.pro.app.util.AppUtils.dpToPx
import com.all.pdfreader.pro.app.util.AppUtils.printPdfFile
import com.all.pdfreader.pro.app.util.AppUtils.setClickWithAnimation
import com.all.pdfreader.pro.app.util.AppUtils.shareFile
import com.all.pdfreader.pro.app.util.FileUtils.toFormatFileSize
import com.all.pdfreader.pro.app.util.FileUtils.toSlashDate
import com.all.pdfreader.pro.app.util.ToastUtils
import com.all.pdfreader.pro.app.viewmodel.PdfViewModel
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import java.io.File

class ListMoreDialogFragment(val filePath: String) : BottomSheetDialogFragment() {

    private lateinit var binding: DialogListMoreBinding
    private val viewModel: PdfViewModel by activityViewModels()
    private lateinit var pdfDocument: PdfDocumentEntity
    private var isFavorite: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = DialogListMoreBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            ?.setBackgroundResource(R.drawable.dr_rc_top_12_bg_white)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.pdfDocument.observe(this) { document ->
            document?.let {
                pdfDocument = it
                isFavorite = pdfDocument.isFavorite
                initUi()
                setupOnClick()
            } ?: run {
                showToast(getString(R.string.file_not))
                dismiss()
            }
        }
        viewModel.getPDFDocument(filePath)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    private fun initUi() {
        when (tag) {
            HomeFrag.FRAG_TAG -> {
                binding.removeRecentBtn.visibility = View.GONE
                binding.setPasswordBtn.visibility = View.VISIBLE
                binding.deleteFileBtn.visibility = View.VISIBLE
                binding.shareBtn.visibility = View.VISIBLE
                binding.gotoPageBtn.visibility = View.GONE
            }

            RecentlyFrag.FRAG_TAG -> {
                binding.removeRecentBtn.visibility = View.VISIBLE
                binding.setPasswordBtn.visibility = View.VISIBLE
                binding.deleteFileBtn.visibility = View.VISIBLE
                binding.shareBtn.visibility = View.VISIBLE
                binding.gotoPageBtn.visibility = View.GONE
            }

            FavoriteFrag.FRAG_TAG -> {
                binding.removeRecentBtn.visibility = View.GONE
                binding.setPasswordBtn.visibility = View.VISIBLE
                binding.deleteFileBtn.visibility = View.VISIBLE
                binding.shareBtn.visibility = View.VISIBLE
                binding.gotoPageBtn.visibility = View.GONE
            }

            PdfViewActivity.FRAG_TAG -> {
                binding.removeRecentBtn.visibility = View.GONE
                binding.setPasswordBtn.visibility = View.GONE
                binding.deleteFileBtn.visibility = View.GONE
                binding.shareBtn.visibility = View.GONE
                binding.gotoPageBtn.visibility = View.VISIBLE
            }
        }
        binding.tvFileName.text = pdfDocument.fileName
        binding.tvFileSize.text = pdfDocument.fileSize.toFormatFileSize()
        binding.tvFileDate.text = pdfDocument.lastModified.toSlashDate()
        if (pdfDocument.isPassword) {
            binding.lockLayout.visibility = View.VISIBLE
            binding.tvFileImg.visibility = View.GONE
        } else {
            binding.lockLayout.visibility = View.GONE
            binding.tvFileImg.visibility = View.VISIBLE
            Glide.with(binding.root).load(pdfDocument.thumbnailPath)
                .transform(CenterCrop(), RoundedCorners(4.dpToPx(binding.root.context)))
                .into(binding.tvFileImg)
        }
        updateCollectUi(isFavorite)
        updatePasswordUi(pdfDocument.isPassword)
    }

    private fun setupOnClick() {
        binding.collectBtn.setClickWithAnimation(duration = 250) {
            isFavorite = !isFavorite
            updateCollectUi(isFavorite)
            viewModel.saveCollectState(pdfDocument.filePath, isFavorite)
            dismiss()
        }
        binding.renameFileBtn.setOnClickListener {
            RenameDialogFragment(RenameType.FILE).show(
                parentFragmentManager, "ListMoreDialogFragment"
            )
            dismiss()
        }
        binding.deleteFileBtn.setOnClickListener {
            PromptDialogFragment(
                getString(R.string.delete_file_title),
                getString(R.string.delete_file_desc),
                onOkClick = {
                    viewModel.deleteFile(pdfDocument.filePath)
                }).show(parentFragmentManager, "deleteFile")
            dismiss()
        }
        binding.detailsBtn.setOnClickListener {
            FileDetailsDialogFragment().show(parentFragmentManager, "FileDetailsDialogFragment")
            dismiss()
        }
        binding.shareBtn.setOnClickListener {
            shareFile(requireActivity(), File(pdfDocument.filePath))
            dismiss()
        }
        binding.printBtn.setOnClickListener {
            val result = printPdfFile(requireActivity(), Uri.fromFile(File(pdfDocument.filePath)))
            when (result) {
                PrintResult.DeviceNotSupported -> {
                    ToastUtils.show(requireActivity(),getString(R.string.device_does_not_support_printing))
                }

                is PrintResult.Error -> {
                    ToastUtils.show(requireActivity(),getString(R.string.pdf_cannot_print_error))
                }

                PrintResult.MalformedPdf -> {
                    ToastUtils.show(requireActivity(),getString(R.string.cannot_print_malformed_pdf))
                }

                PrintResult.PasswordRequired -> {
                    ToastUtils.show(requireActivity(),getString(R.string.pdf_cant_print_password_protected))
                }

                PrintResult.Success -> {

                }
            }
            dismiss()
        }
        binding.duplicateFileBtn.setOnClickListener {
            viewModel.duplicateFile(requireActivity(), pdfDocument.filePath)
            dismiss()
        }
        binding.setPasswordBtn.setOnClickListener {
            if (pdfDocument.isPassword) {
                PdfRemovePasswordDialog(pdfDocument.filePath, onOkClick = { password ->
                    viewModel.removePassword(pdfDocument.filePath, password)
                }).show(parentFragmentManager, "PdfRemovePasswordDialog")
            } else {
                PdfSetPasswordDialog(onOkClick = { password ->
                    viewModel.setPassword(pdfDocument.filePath, password)
                }).show(parentFragmentManager, "PdfSetPasswordDialog")
            }
            dismiss()
        }
        binding.removeRecentBtn.setOnClickListener {
            PromptDialogFragment(
                getString(R.string.remove_dialog_title),
                getString(R.string.remove_dialog_desc),
                getString(R.string.remove),
                onOkClick = {
                    viewModel.removeRecent(pdfDocument.filePath)
                }).show(parentFragmentManager, "removeRecent")
            dismiss()
        }
        binding.splitBtn.setOnClickListener {
            val intent = SplitPdfActivity.createIntent(requireActivity(), pdfDocument.filePath)
            startActivity(intent)
            dismiss()
        }
        binding.gotoPageBtn.setOnClickListener {
            GotoPageDialogFragment().show(parentFragmentManager, "GotoPage")
            dismiss()
        }
        binding.mergeBtn.setOnClickListener {
            val list = arrayListOf(pdfDocument)
            val intent = PdfPickerActivity.createIntent(
                requireActivity(), PdfPickerSource.MERGE,
                MergePdfActivity.TAG_TOW, list
            )
            startActivity(intent)
            dismiss()
        }
        binding.pdfToImgBtn.setOnClickListener {
            val intent = PdfToImageActivity.createIntent(requireActivity(), pdfDocument.filePath,
                PdfPickerSource.PDF_TO_IMAGES)
            startActivity(intent)
            dismiss()
        }
        binding.pdfToLongImgBtn.setOnClickListener {
            val intent = PdfToImageActivity.createIntent(requireActivity(), pdfDocument.filePath,
                PdfPickerSource.TO_LONG_IMAGE)
            startActivity(intent)
            dismiss()
        }
    }

    private fun updateCollectUi(b: Boolean) {
        if (b) {
            binding.collectIv.setImageResource(R.drawable.collected)
        } else {
            binding.collectIv.setImageResource(R.drawable.collect_red)
        }
    }

    private fun updatePasswordUi(b: Boolean) {
        if (b) {
            binding.passwordIv.setImageResource(R.drawable.unlock)
            binding.passwordTv.text = getString(R.string.remove_password)
        } else {
            binding.passwordIv.setImageResource(R.drawable.lock_red)
            binding.passwordTv.text = getString(R.string.set_password)
        }
    }

    private fun showToast(message: String) {
        ToastUtils.show(requireActivity(), message)
    }
}