package com.all.pdfreader.pdf.reader.ui.dialog

import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import com.all.pdfreader.pdf.reader.R
import com.all.pdfreader.pdf.reader.databinding.DialogListMoreBinding
import com.all.pdfreader.pdf.reader.model.PdfPickerSource
import com.all.pdfreader.pdf.reader.model.PrintResult
import com.all.pdfreader.pdf.reader.model.RenameType
import com.all.pdfreader.pdf.reader.room.entity.PdfDocumentEntity
import com.all.pdfreader.pdf.reader.ui.act.MergePdfActivity
import com.all.pdfreader.pdf.reader.ui.act.PdfPickerActivity
import com.all.pdfreader.pdf.reader.ui.act.PdfToImageActivity
import com.all.pdfreader.pdf.reader.ui.act.PdfViewActivity
import com.all.pdfreader.pdf.reader.ui.act.SplitPdfActivity
import com.all.pdfreader.pdf.reader.ui.fragment.FavoriteFrag
import com.all.pdfreader.pdf.reader.ui.fragment.HomeFrag
import com.all.pdfreader.pdf.reader.ui.fragment.RecentlyFrag
import com.all.pdfreader.pdf.reader.util.AnalyticsUtils
import com.all.pdfreader.pdf.reader.util.AppUtils.dpToPx
import com.all.pdfreader.pdf.reader.util.AppUtils.printPdfFile
import com.all.pdfreader.pdf.reader.util.AppUtils.setClickWithAnimation
import com.all.pdfreader.pdf.reader.util.AppUtils.shareFile
import com.all.pdfreader.pdf.reader.util.FileUtils.toFormatFileSize
import com.all.pdfreader.pdf.reader.util.FileUtils.toSlashDate
import com.all.pdfreader.pdf.reader.util.ToastUtils
import com.all.pdfreader.pdf.reader.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() : BottomSheetDialogFragment() {
    companion object {
        private const val ARG_FILE_PATH = "arg_file_path"
        fun newInstance(filePath: String): ListMoreDialogFragment {
            val fragment = ListMoreDialogFragment()
            val args = Bundle()
            args.putString(ARG_FILE_PATH, filePath)
            fragment.arguments = args
            return fragment
        }
    }

    private val filePath: String
        get() = arguments?.getString(ARG_FILE_PATH) ?: ""

    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 {
            val renameDialogFragment = RenameDialogFragment.newInstance(RenameType.FILE)
            renameDialogFragment.show(
                parentFragmentManager, "ListMoreDialogFragment"
            )
            dismiss()
        }
        binding.deleteFileBtn.setOnClickListener {
            val promptDialogFragment = PromptDialogFragment.newInstance(
                title =  getString(R.string.delete_file_title),
                desc = getString(R.string.delete_file_desc)
            )
            promptDialogFragment.onOkClick = {
                viewModel.deleteFile(pdfDocument.filePath)
            }
            promptDialogFragment.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 {
            AnalyticsUtils.logEvent(AnalyticsUtils.Event.FILE_COPY_CK)
            viewModel.duplicateFile(requireActivity(), pdfDocument.filePath)
            dismiss()
        }
        binding.setPasswordBtn.setOnClickListener {
            if (pdfDocument.isPassword) {
                val pdfRemovePasswordDialog = PdfRemovePasswordDialog.newInstance(pdfDocument.filePath)
                pdfRemovePasswordDialog.onOkClick = { password ->
                    viewModel.removePassword(pdfDocument.filePath, password)
                }
                pdfRemovePasswordDialog.show(parentFragmentManager, "PdfRemovePasswordDialog")
            } else {
                val pdfSetPasswordDialog = PdfSetPasswordDialog.newInstance()
                pdfSetPasswordDialog.onOkClick = { password ->
                    viewModel.setPassword(pdfDocument.filePath, password)
                }
                pdfSetPasswordDialog.show(parentFragmentManager, "PdfSetPasswordDialog")
            }
            dismiss()
        }
        binding.removeRecentBtn.setOnClickListener {
            AnalyticsUtils.logEvent(AnalyticsUtils.Event.REMOVE_CK)

            val promptDialogFragment = PromptDialogFragment.newInstance(
                title =  getString(R.string.remove_dialog_title),
                desc = getString(R.string.remove_dialog_desc),
                okBtnText = getString(R.string.remove)
            )
            promptDialogFragment.onOkClick = {
                viewModel.removeRecent(pdfDocument.filePath)
                AnalyticsUtils.logEvent(AnalyticsUtils.Event.REMOVE_SUCCESS)
            }
            promptDialogFragment.show(parentFragmentManager, "removeRecent")
            dismiss()
        }
        binding.splitBtn.setOnClickListener {
            val intent = SplitPdfActivity.createIntent(requireActivity(), pdfDocument.filePath)
            startActivity(intent)
            dismiss()
        }
        binding.gotoPageBtn.setOnClickListener {
            AnalyticsUtils.logEvent(AnalyticsUtils.Event.PAGE_JUMP_CK)
            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)
    }
}