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

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.all.pdfreader.pro.app.PRApp
import com.all.pdfreader.pro.app.R
import com.all.pdfreader.pro.app.databinding.ActivityMainBinding
import com.all.pdfreader.pro.app.model.FileActionEvent
import com.all.pdfreader.pro.app.model.FragmentType
import com.all.pdfreader.pro.app.model.PdfPickerSource
import com.all.pdfreader.pro.app.ui.dialog.PermissionDialogFragment
import com.all.pdfreader.pro.app.ui.dialog.ProgressDialogFragment
import com.all.pdfreader.pro.app.ui.dialog.PromptDialogFragment
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.ui.fragment.ToolsFrag
import com.all.pdfreader.pro.app.ui.view.CustomSwitchButton
import com.all.pdfreader.pro.app.ui.view.CustomSwitchButton.OnCheckedChangeListener
import com.all.pdfreader.pro.app.util.AppUtils
import com.all.pdfreader.pro.app.util.AppUtils.setClickWithAnimation
import com.all.pdfreader.pro.app.util.AppUtils.setOnSingleClickListener
import com.all.pdfreader.pro.app.util.PdfScanner
import com.all.pdfreader.pro.app.util.StoragePermissionHelper
import com.all.pdfreader.pro.app.viewmodel.PdfViewModel
import com.all.pdfreader.pro.app.viewmodel.observeEvent
import kotlinx.coroutines.launch
import java.io.File

class MainActivity : BaseActivity(), PermissionDialogFragment.PermissionCallback,
    PermissionDialogFragment.CloseCallback, HomeFrag.OnItemLongClickListener,
    RecentlyFrag.OnItemLongClickListener, FavoriteFrag.OnItemLongClickListener {

    override val TAG: String = "MainActivity"

    private lateinit var binding: ActivityMainBinding
    private val pdfRepository = getRepository()
    private lateinit var pdfScanner: PdfScanner
    private val homeFragment = HomeFrag()
    private val recentlyFragment = RecentlyFrag()
    private val favoriteFragment = FavoriteFrag()
    private val toolsFragment = ToolsFrag()
    private var activeFragment: Fragment = homeFragment
    private val fragmentTag = "ACTIVE_FRAGMENT"
    private val viewModel by lazy { ViewModelProvider(this)[PdfViewModel::class.java] }
    private var progressDialog: ProgressDialogFragment? = null
    private var fragmentType = FragmentType.HOME

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setupDoubleBackExit()
        initObserve()
        setupFragments()
        setupNavigation()
        pdfScanner = PdfScanner(this, pdfRepository)
        if (savedInstanceState != null) {
            val restoredFragment =
                supportFragmentManager.getFragment(savedInstanceState, fragmentTag)
            if (restoredFragment != null) {
                activeFragment = restoredFragment
            }
            supportFragmentManager.beginTransaction().hide(homeFragment).hide(recentlyFragment)
                .hide(favoriteFragment).hide(toolsFragment).show(activeFragment).commit()
        }
        updateMultiSelectUi(false, fragmentType)
    }

    private fun initObserve() {
        //观察其余操作
        viewModel.fileActionEvent.observeEvent<FileActionEvent.Rename>(this) { event ->
            if (event.renameResult.success) {
                showToast(getString(R.string.rename_successfully))
            } else {
                showToast(event.renameResult.errorMessage.toString())
            }
        }
        viewModel.fileActionEvent.observeEvent<FileActionEvent.Delete>(this) { event ->
            if (event.deleteResult.success) {
                showToast(getString(R.string.delete_successfully))
            } else {
                showToast(event.deleteResult.errorMessage.toString())
            }
        }
        viewModel.fileActionEvent.observeEvent<FileActionEvent.Favorite>(this) { event ->
            if (event.isFavorite) {
                showToast(getString(R.string.added_to_favorites))
            } else {
                showToast(getString(R.string.removed_from_favorites))
            }
        }
        viewModel.fileActionEvent.observeEvent<FileActionEvent.Duplicate>(this) { event ->
            if (event.file != null) {
                showToast(getString(R.string.duplicate_created_successfully))
            } else {
                showToast(getString(R.string.duplicate_created_failed))
            }
        }
        viewModel.fileActionEvent.observeEvent<FileActionEvent.SetPassword>(this) { event ->
            when (event.status) {
                FileActionEvent.SetPassword.Status.START -> {
                    progressDialog = ProgressDialogFragment()
                    progressDialog?.show(supportFragmentManager, "progressDialog")
                }

                FileActionEvent.SetPassword.Status.COMPLETE -> {
                    progressDialog?.dismiss()
                    progressDialog = null
                    if (event.success == true) {
                        showToast(getString(R.string.set_password_successfully))
                    } else {
                        showToast(getString(R.string.set_password_failed))
                    }
                }
            }
        }
        viewModel.fileActionEvent.observeEvent<FileActionEvent.RemovePassword>(this) { event ->
            when (event.status) {
                FileActionEvent.RemovePassword.Status.START -> {
                    progressDialog = ProgressDialogFragment()
                    progressDialog?.show(supportFragmentManager, "progressDialog")
                }

                FileActionEvent.RemovePassword.Status.COMPLETE -> {
                    progressDialog?.dismiss()
                    progressDialog = null
                    if (event.success == true) {
                        showToast(getString(R.string.remove_password_successfully))
                    } else {
                        showToast(getString(R.string.remove_password_failed))
                    }
                }
            }
        }
        viewModel.fileActionEvent.observeEvent<FileActionEvent.DeleteAll>(this) { event ->
            when (event.status) {
                FileActionEvent.DeleteAll.Status.START -> {
                    progressDialog = ProgressDialogFragment()
                    progressDialog?.show(supportFragmentManager, "progressDialog")
                }

                FileActionEvent.DeleteAll.Status.COMPLETE -> {
                    progressDialog?.dismiss()
                    progressDialog = null
                    event.deleteResult?.let {
                        if (event.deleteResult.success) {
                            showToast(getString(R.string.delete_successfully))
                        } else {
                            showToast(event.deleteResult.errorMessage.toString())
                        }
                    }
                }
            }
        }
    }

    private fun setupFragments() {
        supportFragmentManager.beginTransaction().add(R.id.fragment_fl, toolsFragment, "TOOLS")
            .hide(toolsFragment).add(R.id.fragment_fl, favoriteFragment, "FAVORITE")
            .hide(favoriteFragment).add(R.id.fragment_fl, recentlyFragment, "RECENTLY")
            .hide(recentlyFragment).add(R.id.fragment_fl, homeFragment, "HOME").commit()
    }

    //按钮点击事件
    private fun setupNavigation() {
        binding.switchScreenOn.setChecked(appStore.keepScreenOn)

        binding.homeLlBtn.setOnSingleClickListener { switchFragment(homeFragment) }
        binding.recentlyLlBtn.setOnSingleClickListener { switchFragment(recentlyFragment) }
        binding.favoriteLlBtn.setOnSingleClickListener { switchFragment(favoriteFragment) }
        binding.toolsLayoutBtn.setOnSingleClickListener { switchFragment(toolsFragment) }

        binding.pnGoBtn.setOnSingleClickListener {
            //直接跳转到权限设置页面
            requestPermissions()
        }

        binding.sidebarBtn.setClickWithAnimation {
            binding.drawerLayout.openDrawer(binding.drawerView)
        }
        //防止事件穿透
        binding.drawerView.setOnClickListener { }

        binding.searchBtn.setClickWithAnimation {
            startActivity(SearchActivity.createIntent(this, PdfPickerSource.NONE))
        }

        binding.multiSelectBackBtn.setOnSingleClickListener {
            exitAllMultiSelect()
        }
        binding.multiSelectBtn.setOnClickListener {
            when (activeFragment) {
                is HomeFrag -> {
                    (activeFragment as HomeFrag).setupMultiSelect()
                }

                is RecentlyFrag -> {
                    (activeFragment as RecentlyFrag).setupMultiSelect()
                }

                is FavoriteFrag -> {
                    (activeFragment as FavoriteFrag).setupMultiSelect()
                }
            }
        }
        binding.multiSelectAllBtn.setOnSingleClickListener {
            when (activeFragment) {
                is HomeFrag -> {
                    homeFragment.adapter.toggleSelectAll()
                    updateSelectNumber(homeFragment.adapter.getSelectedItems().size)
                }

                is RecentlyFrag -> {
                    recentlyFragment.adapter.toggleSelectAll()
                    updateSelectNumber(recentlyFragment.adapter.getSelectedItems().size)
                }

                is FavoriteFrag -> {
                    favoriteFragment.adapter.toggleSelectAll()
                    updateSelectNumber(favoriteFragment.adapter.getSelectedItems().size)
                }
            }

        }
        binding.multiSelectDeleteBtn.setOnSingleClickListener {
            val selectedItems = homeFragment.adapter.getSelectedItems()
            if (selectedItems.isNotEmpty()) {
                val filesToDelete = selectedItems.map { File(it.filePath) }
                var title = getString(R.string.delete_file_title)
                var desc = getString(R.string.delete_file_desc)
                if (selectedItems.size > 1) {
                    title = getString(R.string.delete_all_file_title)
                    desc = getString(R.string.delete_all_file_desc)
                }
                PromptDialogFragment(
                    title, desc, onOkClick = {
                        viewModel.deleteFiles(filesToDelete)
                        exitAllMultiSelect()
                    }).show(supportFragmentManager, "deleteFiles")
            }
        }
        binding.multiSelectMergeBtn.setOnSingleClickListener {
            val selectedItems = when (activeFragment) {
                is HomeFrag -> (activeFragment as HomeFrag).adapter.getSelectedItems()
                is FavoriteFrag -> (activeFragment as FavoriteFrag).adapter.getSelectedItems()
                is RecentlyFrag -> (activeFragment as RecentlyFrag).adapter.getSelectedItems()
                else -> emptyList()
            }
            if (selectedItems.isNotEmpty()) {
                val intent = MergePdfActivity.createIntent(this, ArrayList(selectedItems))
                startActivity(intent)
                exitAllMultiSelect()
            }
        }
        binding.multiSelectRemoveBtn.setOnSingleClickListener {
            val selectedItems = recentlyFragment.adapter.getSelectedItems()
            if (selectedItems.isNotEmpty()) {
                val filePaths = selectedItems.map { it.filePath }
                PromptDialogFragment(
                    getString(R.string.remove_dialog_title),
                    getString(R.string.remove_dialog_desc),
                    getString(R.string.remove),
                    onOkClick = {
                        viewModel.removeRecentAll(filePaths)
                        exitAllMultiSelect()
                    }).show(supportFragmentManager, "removeRecent")
            }
        }
        binding.multiSelectUnFavoriteBtn.setOnSingleClickListener {
            val selectedItems = favoriteFragment.adapter.getSelectedItems()
            if (selectedItems.isNotEmpty()) {
                val filePaths = selectedItems.map { it.filePath }
                viewModel.cancelCollectState(filePaths)
                exitAllMultiSelect()
            }
        }
        binding.faqBtn.setOnClickListener {
            val intent = Intent(this, FAQActivity::class.java)
            startActivity(intent)
            binding.drawerLayout.closeDrawer(binding.drawerView)
        }
        binding.switchScreenOn.setOnCheckedChangeListener(object : OnCheckedChangeListener {
            override fun onCheckedChanged(view: CustomSwitchButton?, isChecked: Boolean) {
                view?.setChecked(isChecked)
                appStore.keepScreenOn = isChecked
                setKeepScreenOn(isChecked)
            }
        })
        binding.shareAppBtn.setOnClickListener {
            AppUtils.shareAppInfo(this)
            binding.drawerLayout.closeDrawer(binding.drawerView)
        }
        binding.privacyPolicyBtn.setOnClickListener {
            val intent = Intent(this, PrivacyPolicyActivity::class.java)
            startActivity(intent)
            binding.drawerLayout.closeDrawer(binding.drawerView)
        }
    }

    private fun setKeepScreenOn(b: Boolean) {
        if (b) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        } else {
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        }
    }

    private fun switchFragment(target: Fragment) {
        if (target == activeFragment) return
        supportFragmentManager.beginTransaction().hide(activeFragment).show(target).commit()
        activeFragment = target
        updateSelectedNav(target)
    }

    private fun updateSelectedNav(fragment: Fragment) {
        if (fragment is ToolsFrag) {//工具界面不展示权限与搜索和多选
            binding.pnLayout.visibility = View.GONE
            binding.topButtonLayout.visibility = View.GONE
        } else {
            binding.topButtonLayout.visibility = View.VISIBLE
            if (!StoragePermissionHelper.hasBasicStoragePermission(this)) {
                binding.pnLayout.visibility = View.VISIBLE
            }
        }
        if (StoragePermissionHelper.hasBasicStoragePermission(this)) {
            binding.topButtonLayout.visibility = View.VISIBLE
        } else {
            binding.topButtonLayout.visibility = View.GONE
        }
        when (fragment) {
            is HomeFrag -> {
                binding.homeIv.setImageResource(R.drawable.icon_home_sel_on)
                binding.recentlyIv.setImageResource(R.drawable.icon_recently_sel_off)
                binding.favoriteIv.setImageResource(R.drawable.collect)
                binding.toolsIv.setImageResource(R.drawable.icon_tools_sel_off)

                binding.homeTv.setTextColor(getColor(R.color.icon_on))
                binding.recentlyTv.setTextColor(getColor(R.color.icon_off))
                binding.favoriteTv.setTextColor(getColor(R.color.icon_off))
                binding.toolsTv.setTextColor(getColor(R.color.icon_off))
            }

            is RecentlyFrag -> {
                binding.homeIv.setImageResource(R.drawable.icon_home_sel_off)
                binding.recentlyIv.setImageResource(R.drawable.icon_recently_sel_on)
                binding.favoriteIv.setImageResource(R.drawable.collect)
                binding.toolsIv.setImageResource(R.drawable.icon_tools_sel_off)

                binding.homeTv.setTextColor(getColor(R.color.icon_off))
                binding.recentlyTv.setTextColor(getColor(R.color.icon_on))
                binding.favoriteTv.setTextColor(getColor(R.color.icon_off))
                binding.toolsTv.setTextColor(getColor(R.color.icon_off))
            }

            is FavoriteFrag -> {
                binding.homeIv.setImageResource(R.drawable.icon_home_sel_off)
                binding.recentlyIv.setImageResource(R.drawable.icon_recently_sel_off)
                binding.favoriteIv.setImageResource(R.drawable.collected)
                binding.toolsIv.setImageResource(R.drawable.icon_tools_sel_off)

                binding.homeTv.setTextColor(getColor(R.color.icon_off))
                binding.recentlyTv.setTextColor(getColor(R.color.icon_off))
                binding.favoriteTv.setTextColor(getColor(R.color.icon_on))
                binding.toolsTv.setTextColor(getColor(R.color.icon_off))
            }

            is ToolsFrag -> {
                binding.homeIv.setImageResource(R.drawable.icon_home_sel_off)
                binding.recentlyIv.setImageResource(R.drawable.icon_recently_sel_off)
                binding.favoriteIv.setImageResource(R.drawable.collect)
                binding.toolsIv.setImageResource(R.drawable.icon_tools_sel_on)

                binding.homeTv.setTextColor(getColor(R.color.icon_off))
                binding.recentlyTv.setTextColor(getColor(R.color.icon_off))
                binding.favoriteTv.setTextColor(getColor(R.color.icon_off))
                binding.toolsTv.setTextColor(getColor(R.color.icon_on))
            }
        }

    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        supportFragmentManager.putFragment(outState, fragmentTag, activeFragment)
    }

    override fun onResume() {
        super.onResume()
        logDebug("main onResume")
        if (StoragePermissionHelper.hasBasicStoragePermission(this)) {
            // 有授权才初始化文件变化监听器
            PRApp.getInstance().startFileChangeObserving()
            scanningStrategy()
            binding.pnLayout.visibility = View.GONE
        } else {
            binding.pnLayout.visibility = View.VISIBLE
            val dialog = PermissionDialogFragment()
            //如果之前展示过授权对话框，则不再展示
            if (!appStore.isShowPermissionsDialogPrompt) {
                dialog.show(supportFragmentManager, TAG)
            }
        }
        updateSelectedNav(activeFragment)
    }

    private fun scanningStrategy() {
        if (StoragePermissionHelper.hasBasicStoragePermission(this)) {
            lifecycleScope.launch {
                pdfScanner.scanAndLoadPdfFiles(PRApp.isNeedFullScan)
            }
        } else {
            logDebug("❌ 权限不足，跳过扫描")
        }
    }

    private fun exitAllMultiSelect() {
        homeFragment.exitMultiSelectMode()
        favoriteFragment.exitMultiSelectMode()
        recentlyFragment.exitMultiSelectMode()
        updateMultiSelectUi(false, fragmentType)
    }

    // 授权后续操作
    override fun onPermissionGranted() {
        logDebug("main onPermissionGranted")
        //授权成功后：隐藏授权提示，开始扫描文件
        binding.pnLayout.visibility = View.GONE
        PRApp.getInstance().startFileChangeObserving()
        scanningStrategy()
    }

    override fun onClose() {
        logDebug("main onClose")
        //关闭对话框进行权限入口显示。
        if (StoragePermissionHelper.hasBasicStoragePermission(this)) {
            binding.pnLayout.visibility = View.GONE
        } else {
            binding.pnLayout.visibility = View.VISIBLE
        }
    }

    private fun requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            StoragePermissionHelper.openAllFilesAccessSettings(this)
        } else {
            val permissions = StoragePermissionHelper.getRequiredPermissions()
            multiplePermissionsLauncher.launch(permissions)
        }
    }

    private val multiplePermissionsLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            val allGranted = permissions.values.all { it }
            if (allGranted) {
                onPermissionGranted()
            } else {
                onClose()
            }
        }

    override fun onItemLongClicked(type: FragmentType) {
        fragmentType = type
        updateMultiSelectUi(true, fragmentType)
        updateSelectNumber(homeFragment.adapter.getSelectedItems().size)
    }

    private fun updateMultiSelectUi(b: Boolean, type: FragmentType) {
        if (b) {
            binding.apply {
                multiSelectTopLayout.visibility = View.VISIBLE
                multiSelectBottomLayout.visibility = View.VISIBLE
                navigationLayout.visibility = View.GONE
                topLayout.visibility = View.GONE
            }
            when (type) {
                FragmentType.HOME -> {
                    binding.multiSelectRemoveBtn.visibility = View.GONE
                    binding.multiSelectUnFavoriteBtn.visibility = View.GONE
                }

                FragmentType.RECENTLY -> {
                    binding.multiSelectRemoveBtn.visibility = View.VISIBLE
                    binding.multiSelectUnFavoriteBtn.visibility = View.GONE
                }

                FragmentType.FAVORITE -> {
                    binding.multiSelectRemoveBtn.visibility = View.GONE
                    binding.multiSelectUnFavoriteBtn.visibility = View.VISIBLE
                }
            }
        } else {
            binding.apply {
                multiSelectTopLayout.visibility = View.GONE
                multiSelectBottomLayout.visibility = View.GONE
                navigationLayout.visibility = View.VISIBLE
                topLayout.visibility = View.VISIBLE
            }
        }
    }

    fun updateSelectNumber(number: Int) {
        binding.multiSelectNumberTv.text = getString(R.string.selected_page, number)
        if (number >= 1) {
            binding.multiSelectDeleteIv.setImageResource(R.drawable.icon_delete_sel_on)
            binding.multiSelectDeleteTv.setTextColor(getColor(R.color.black))
            binding.multiSelectDeleteBtn.isClickable = true
            binding.multiSelectRemoveIv.setImageResource(R.drawable.icon_remove_sel_on)
            binding.multiSelectRemoveTv.setTextColor(getColor(R.color.black))
            binding.multiSelectRemoveBtn.isClickable = true
            binding.multiSelectUnFavoriteIv.setImageResource(R.drawable.icon_un_favorite_sel_on)
            binding.multiSelectUnFavoriteTv.setTextColor(getColor(R.color.black))
            binding.multiSelectUnFavoriteBtn.isClickable = true
        } else {
            binding.multiSelectDeleteIv.setImageResource(R.drawable.icon_delete_sel_off)
            binding.multiSelectDeleteTv.setTextColor(getColor(R.color.icon_sel_off_color))
            binding.multiSelectDeleteBtn.isClickable = false
            binding.multiSelectRemoveIv.setImageResource(R.drawable.icon_remove_sel_off)
            binding.multiSelectRemoveTv.setTextColor(getColor(R.color.icon_sel_off_color))
            binding.multiSelectRemoveBtn.isClickable = false
            binding.multiSelectUnFavoriteIv.setImageResource(R.drawable.icon_un_favorite_sel_off)
            binding.multiSelectUnFavoriteTv.setTextColor(getColor(R.color.icon_sel_off_color))
            binding.multiSelectUnFavoriteBtn.isClickable = false
        }

        if (number >= 2) {
            binding.multiSelectMergeIv.setImageResource(R.drawable.icon_merge_sel_on)
            binding.multiSelectMergeTv.setTextColor(getColor(R.color.black))
            binding.multiSelectMergeBtn.isClickable = true
        } else {
            binding.multiSelectMergeIv.setImageResource(R.drawable.icon_merge_sel_off)
            binding.multiSelectMergeTv.setTextColor(getColor(R.color.icon_sel_off_color))
            binding.multiSelectMergeBtn.isClickable = false
        }
    }

    private var lastBackPressedTime: Long = 0
    private val EXIT_INTERVAL = 2000L // 2 秒内双击退出

    private fun setupDoubleBackExit() {
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                val currentTime = System.currentTimeMillis()
                if (currentTime - lastBackPressedTime < EXIT_INTERVAL) {
                    // 双击退出
                    isEnabled = false // 解除拦截
                    onBackPressedDispatcher.onBackPressed() // 调用系统默认返回逻辑
                } else {
                    lastBackPressedTime = currentTime
                    showToast(getString(R.string.press_again_to_exit))
                }
            }
        })
    }
}
