package com.ux.video.file.filerecovery.recovery.ui.recoveryphoto

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.ux.video.file.filerecovery.R
import com.ux.video.file.filerecovery.base.BaseFragment
import com.ux.video.file.filerecovery.databinding.FragmentRecoveryPhotoBinding
import com.ux.video.file.filerecovery.db.ObjectBoxManager

import com.ux.video.file.filerecovery.db.ResultDataFiles
import com.ux.video.file.filerecovery.db.targetFile
import com.ux.video.file.filerecovery.detail.DetailsActivity
import com.ux.video.file.filerecovery.main.ScanSelectTypeActivity
import com.ux.video.file.filerecovery.sort.SortDisplayChildAdapter
import com.ux.video.file.filerecovery.sort.RecoverOrDeleteManager
import com.ux.video.file.filerecovery.utils.Common
import com.ux.video.file.filerecovery.utils.Common.KEY_SCAN_TYPE
import com.ux.video.file.filerecovery.utils.ExtendFunctions.dpToPx
import com.ux.video.file.filerecovery.utils.FileType


class RecoveredFragment : BaseFragment<FragmentRecoveryPhotoBinding>() {

    companion object {
        private const val ARG_FILE_TYPE = "arg_file_type"

        fun newInstance(fileType: Int): RecoveredFragment {
            val fragment = RecoveredFragment()
            val args = Bundle().apply {
                putInt(ARG_FILE_TYPE, fileType)
            }
            fragment.arguments = args
            return fragment
        }
    }


    private var fileType: FileType? = null

    private var mAdapter: SortDisplayChildAdapter? = null
    private var selectedList: Set<ResultDataFiles>? = null


    private val sharedViewModel: RecoveryPhotoViewModel by activityViewModels()
    private lateinit var recoveredList: List<ResultDataFiles>


    override fun initBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentRecoveryPhotoBinding =
        FragmentRecoveryPhotoBinding.inflate(inflater, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val i = arguments?.getInt(ARG_FILE_TYPE) ?: FileType.PHOTO.value
        fileType = FileType.from(i)
        binding.run {
            fileType?.let {
                when (it) {
                    FileType.PHOTO -> {
                        layoutEmpty.tvScan.text = getString(R.string.scan_photos)
                        sharedViewModel.photoFiles.observe(viewLifecycleOwner) {
                            initViewVisible(it)
                            setRecoveredData(it, FileType.PHOTO)
                        }
                        sharedViewModel.selectedPhoto.observe(viewLifecycleOwner) { displaySet ->
                            selectedList = displaySet
                            Common.showLog("当前显示筛选数据 选中状态更新: ${displaySet.size}")
                            selectedList?.let {
                                updateSelectStatus(it.size)
                            }

                        }
                    }

                    FileType.VIDEO -> {
                        layoutEmpty.tvScan.text = getString(R.string.scan_videos)
                        sharedViewModel.videoFiles.observe(viewLifecycleOwner) {
                            initViewVisible(it)
                            setRecoveredData(it, FileType.VIDEO )
                        }
                        sharedViewModel.selectedVideo.observe(viewLifecycleOwner) { displaySet ->
                            selectedList = displaySet
                            Common.showLog("当前显示筛选数据 选中状态更新: ${displaySet.size}")
                            selectedList?.let {
                                updateSelectStatus(it.size)
                            }
                        }
                    }

                    FileType.AUDIO -> {
                        layoutEmpty.tvScan.text = getString(R.string.scan_audios)
                        sharedViewModel.audioFiles.observe(viewLifecycleOwner) {
                            initViewVisible(it)
                            setRecoveredData(it,    FileType.AUDIO )
                        }
                        sharedViewModel.selectedAudio.observe(viewLifecycleOwner) { displaySet ->
                            selectedList = displaySet
                            Common.showLog("当前显示筛选数据 选中状态更新: ${displaySet.size}")
                            selectedList?.let {
                                updateSelectStatus(it.size)
                            }
                        }
                    }

                    FileType.DOCUMENT -> {
                        layoutEmpty.tvScan.text = getString(R.string.scan_documents)
                        sharedViewModel.documentsFiles.observe(viewLifecycleOwner) {
                            initViewVisible(it)
                            setRecoveredData(it, FileType.DOCUMENT)
                        }
                        sharedViewModel.selectedDocuments.observe(viewLifecycleOwner) { displaySet ->
                            selectedList = displaySet
                            Common.showLog("当前显示筛选数据 选中状态更新: ${displaySet.size}")
                            selectedList?.let {
                                updateSelectStatus(it.size)
                            }
                        }
                    }

                }
            }
        }
        updateSelectStatus(0)
        initClick()

    }


    private fun initViewVisible(list: List<ResultDataFiles>) {
        recoveredList = list
        binding.run {
            recyclerView.isVisible = list.isNotEmpty()
            layoutEmpty.relativeEmptyMain.isVisible = !list.isNotEmpty()
            layoutBottom.run {
                bottomMainLayout.isVisible = list.isNotEmpty()
//                tvRight.text = getString(R.string.share)
            }
            tvAllSelect.isVisible = list.isNotEmpty()
        }
    }

    private fun updateSelectStatus(selectedCounts: Int) {
        binding.run {
            selectedCounts.let {
                tvAllSelect.isSelected = it == mAdapter?.itemCount
                if (it <= 0) {
                    layoutBottom.tvLeft.isEnabled = false
                    layoutBottom.tvRight.isEnabled = false
                } else {
                    layoutBottom.tvLeft.isEnabled = true
                    layoutBottom.tvRight.isEnabled = true
                }
                layoutBottom.tvLeft.text = getString(R.string.delete_placeholder, it)
                layoutBottom.tvRight.text = getString(R.string.share_placeholder, it)

            }
        }

    }

    private fun setRecoveredData(list: List<ResultDataFiles>, fileType: FileType) {

        mAdapter = SortDisplayChildAdapter(
            mContext = requireContext(),
            fileType = fileType,
            mColumns = 2,
            viewModel = sharedViewModel,
            onSelectedUpdate = { resultPhotosFiles, isAdd, allSelected ->
                fileType?.let { sharedViewModel.toggleSelection(it, isAdd, resultPhotosFiles) }


            },
            hideThumbnailsUpdate = { hide ->

            }) { item ->

            startActivity(
                Intent(
                    requireContext(),
                    DetailsActivity::class.java
                ).apply {
                    putExtra(KEY_SCAN_TYPE, fileType.value)
                    putExtra(DetailsActivity.KEY_CLICK_ITEM, item)
                    putExtra(DetailsActivity.KEY_SHOW_SHARE, true)
                })

        }.apply {
            setData(list)
        }

        binding.recyclerView.run {
            adapter = mAdapter
            when (fileType) {
                FileType.PHOTO, FileType.VIDEO -> {
                    layoutManager = GridLayoutManager(requireContext(), 2)
                    val bPx = 6.dpToPx(context)
                    val aPx = 16.dpToPx(context)
                    val bottom = 75.dpToPx(context)
                    setPadding(aPx, 0, bPx, bottom)
                }


                FileType.AUDIO , FileType.DOCUMENT  -> {
                    layoutManager = LinearLayoutManager(requireContext())
                    val bPx = 6.dpToPx(context)
                    val aPx = 16.dpToPx(context)
                    val bottom = 75.dpToPx(context)
                    setPadding(aPx, 0, bPx, bottom)
                }

            }

        }

    }

    private fun initClick() {
        binding.run {

            fileType?.let { fileType ->
                layoutEmpty.tvScan.setOnClickListener {
                    startActivity(
                        Intent(
                            requireActivity(),
                            ScanSelectTypeActivity::class.java
                        ).apply {
                            putExtra(Common.KEY_FILE_TYPE, fileType.value)
                        })
                    requireActivity().finish()
                }
                tvAllSelect.setOnClickListener {
                    it.isSelected = !it.isSelected
                    mAdapter?.setAllSelected(it.isSelected)

                }
                layoutBottom.tvLeft.setOnClickListener {
                    selectedList?.let {
                        RecoverOrDeleteManager.showConfirmDeleteDialog(
                            fragmentManager = requireActivity().supportFragmentManager,
                            scope = lifecycleScope,
                            selectedSetList = it
                        ) { count ->
                            val removeSelectedFromSizeList =
                                sharedViewModel.removeSelectedFromSizeList(recoveredList, it)
                            ObjectBoxManager.deleteRecoveryFilesAsyncById(
                                lifecycleScope,
                                it.toList()
                            ) {}
                            sharedViewModel.setRecoveredFiles(fileType, removeSelectedFromSizeList)
                            sharedViewModel.clearSelected(fileType)
                            showCustomToast(requireContext())
                        }
                    }
                }

                layoutBottom.tvRight.setOnClickListener {
                    selectedList?.let { list->
                        if (list.size == 1) {
                            list.first().targetFile().let { file ->
                                Common.shareSingleFile(requireActivity(), file, fileType)
                            }
                        } else if (list.isNotEmpty()) {
                            val toList = list.map { it.targetFile() }.toList()
                            Common.shareMultipleFiles(requireActivity(), toList, fileType)
                        }

                    }
                }
            }
        }


    }

    fun showCustomToast(context: Context) {
        val inflater = LayoutInflater.from(context)
        Toast(context).apply {
            duration = Toast.LENGTH_SHORT
            this.view = inflater.inflate(R.layout.dialog_delete_success, null)
            setGravity(Gravity.CENTER_HORIZONTAL or Gravity.TOP, 0, 150.dpToPx(context))
            show()
        }
    }
}