package com.gh.gamecenter.cloudarchive

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.core.widget.doOnTextChanged
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.DialogHelper
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.setRootBackgroundDrawable
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.runOnIoThread
import com.gh.gamecenter.databinding.DialogEditArchiveBinding
import com.gh.gamecenter.databinding.DialogMyArchiveOptionBinding
import com.gh.gamecenter.databinding.DialogShareArchiveBinding
import com.gh.gamecenter.entity.ArchiveEntity
import com.gh.vspace.VArchiveHelper
import com.halo.assistant.HaloApp
import com.lightgame.download.FileUtils
import org.greenrobot.eventbus.EventBus

class MyArchiveOptionDialogFragment(private val mViewModel: CloudArchiveManagerViewModel) : BaseDialogFragment() {

    private lateinit var mBinding: DialogMyArchiveOptionBinding
    private var mType = MyArchiveFragment.Type.MY_ARCHIVE
    private var mGameId = ""
    private var mArchiveEntity: ArchiveEntity? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return DialogMyArchiveOptionBinding.inflate(layoutInflater, null, false).apply {
            mBinding = this
        }.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mGameId = mViewModel.gameId
        mType = MyArchiveFragment.Type.fromString(requireArguments().getString(KEY_ARCHIVE_TYPE, ""))
        mArchiveEntity = requireArguments().getParcelable(KEY_ARCHIVE)

        mBinding.editTv.goneIf(mType != MyArchiveFragment.Type.MY_ARCHIVE)
        mBinding.shareTv.goneIf(mType != MyArchiveFragment.Type.MY_ARCHIVE)
        mBinding.deleteTv.setOnClickListener {
            NewFlatLogUtils.logCloudArchiveDeleteDialogShow()
            DialogHelper.showDialog(
                requireContext(),
                "提示",
                "删除存档数据后将无法恢复，\n" +
                        "是否删除？",
                "确定删除",
                "取消",
                confirmClickCallback = {
                    NewFlatLogUtils.logCloudArchiveDeleteDialogClick("确定")
                    mArchiveEntity?.let { entity ->
                        when (mType) {
                            MyArchiveFragment.Type.MY_ARCHIVE -> {
                                if (VArchiveHelper.isArchiveDownloaded(entity.md5)) {
                                    deleteLocalArchive(entity.md5)
                                }
                                mViewModel.deleteArchive(entity)
                                EventBus.getDefault().post(EBReuse("RefreshShareArchive"))
                            }
                            MyArchiveFragment.Type.MY_DOWNLOAD_ARCHIVE -> {
                                if (VArchiveHelper.isArchiveDownloaded(entity.md5)) {
                                    deleteLocalArchive(entity.md5)
                                    EventBus.getDefault().post(EBReuse("RefreshArchive"))
                                }
                            }
                            MyArchiveFragment.Type.MY_SHARE_ARCHIVE -> {
                                mViewModel.cancelShareArchive(entity)
                            }
                        }
                    }
                },
                cancelClickCallback = {
                    NewFlatLogUtils.logCloudArchiveDeleteDialogClick("取消")
                },
                uiModificationCallback = {
                    it.confirmTv.setTextColor(R.color.theme_red.toColor(requireContext()))
                },
                extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
            )
            dismissAllowingStateLoss()
        }
        mBinding.editTv.setOnClickListener {
            showEditDialog()
            dismissAllowingStateLoss()
        }
        mBinding.shareTv.setOnClickListener {
            NewFlatLogUtils.logCloudArchiveShareDialogShow()
            showShareDialog()
            dismissAllowingStateLoss()
        }
        mBinding.cancelBtn.setOnClickListener {
            dismissAllowingStateLoss()
        }
    }

    private fun deleteLocalArchive(md5: String) {
        VArchiveHelper.deleteArchive(md5)
        val pathName = VArchiveHelper.getArchiveFilePath(md5)
        if (pathName.isNotEmpty()) {
            runOnIoThread { FileUtils.deleteFile(pathName) }
        }
    }

    private fun showEditDialog() {
        val dialog = Dialog(requireActivity())
        val binding = DialogEditArchiveBinding.inflate(layoutInflater)
        binding.run {
            descTv.text = "当前存档名《${mArchiveEntity?.name}》，修改为"
            clearIv.setOnClickListener {
                contentEt.text.clear()
            }
            contentEt.doOnTextChanged { text, _, _, _ ->
                clearIv.goneIf(text?.length == 0)
                confirmTv.isEnabled = text?.length != 0
                confirmTv.alpha = if (text?.length != 0) 1F else 0.4F
            }
            confirmTv.setOnClickListener {
                mArchiveEntity?.let { entity ->
                    mViewModel.editMyArchive(entity.copy(name = contentEt.text.toString().trim()))
                }
                dialog.dismiss()
            }
            cancelTv.setOnClickListener {
                dialog.dismiss()
            }
        }
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.show()
    }

    private fun showShareDialog() {
        val dialog = Dialog(requireActivity())
        val binding = DialogShareArchiveBinding.inflate(layoutInflater)
        binding.run {
            mArchiveEntity?.let {
                titleEt.setText(it.name)
                clearTitleIv.goneIf(it.name.isEmpty())
            }
            clearTitleIv.setOnClickListener {
                titleEt.text.clear()
            }
            clearDescIv.setOnClickListener {
                descEt.text.clear()
            }
            titleEt.doOnTextChanged { text, _, _, _ ->
                clearTitleIv.goneIf(text?.length == 0)
                confirmTv.isEnabled = (text?.length != 0 && descEt.text.isNotEmpty())
                confirmTv.alpha = if (text?.length != 0 && descEt.text.isNotEmpty()) 1F else 0.4F
            }
            descEt.doOnTextChanged { text, _, _, _ ->
                clearDescIv.goneIf(text?.length == 0)
                confirmTv.isEnabled = (text?.length != 0 && titleEt.text.isNotEmpty())
                confirmTv.alpha = if (text?.length != 0 && titleEt.text.isNotEmpty()) 1F else 0.4F
            }
            confirmTv.setOnClickListener {
                mArchiveEntity?.let { entity ->
                    mViewModel.shareArchive(entity, titleEt.text.toString().trim(), descEt.text.toString().trim())
                }
                NewFlatLogUtils.logCloudArchiveShareDialogClick("分享")
                dialog.dismiss()
            }
            cancelTv.setOnClickListener {
                NewFlatLogUtils.logCloudArchiveShareDialogClick("取消")
                dialog.dismiss()
            }
        }
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            dismissAllowingStateLoss()
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val createDialog = super.onCreateDialog(savedInstanceState)
        createDialog.setCanceledOnTouchOutside(true)
        val window = createDialog.window
        window?.setGravity(Gravity.BOTTOM)
        window?.setWindowAnimations(R.style.community_publication_animation)
        return createDialog
    }

    override fun onStart() {
        super.onStart()
        val width = HaloApp.getInstance().application.resources.displayMetrics.widthPixels
        val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        if (::mBinding.isInitialized) {
            mBinding.run {
                root.setRootBackgroundDrawable(R.drawable.background_shape_white_radius_12_top_only)
                line1.setBackgroundColor(R.color.divider.toColor(requireContext()))
                cancelBtn.setTextColor(R.color.text_subtitle.toColor(requireContext()))
            }
        }
    }

    companion object {
        const val KEY_ARCHIVE_TYPE = "archive_type"
        const val KEY_ARCHIVE = "archive"

        fun show(
            activity: AppCompatActivity,
            mViewModel: CloudArchiveManagerViewModel,
            archiveType: MyArchiveFragment.Type,
            archiveEntity: ArchiveEntity
        ) {
            MyArchiveOptionDialogFragment(mViewModel).apply {
                arguments = bundleOf(
                    KEY_ARCHIVE_TYPE to archiveType.value,
                    KEY_ARCHIVE to archiveEntity
                )
            }.show(activity.supportFragmentManager, MyArchiveOptionDialogFragment::class.java.name)
        }
    }
}